A monotonic stack keeps candidates in value order so one new item can settle several earlier questions. In a next-greater scan, smaller unresolved values leave when the current value supplies their first answer. In a previous-smaller scan, larger or equal candidates leave because the current item is closer and at least as useful for later searches.
Each index can enter and leave only once. That gives linear total work even when an individual loop iteration pops many entries. You will use that accounting for greater values, smaller predecessors, compressed demand spans, skyline rectangles, and window maxima. Decide whether equality should pop before coding. A deque adds expiration at the front, while a skyline stack needs a final sentinel to close candidates that never meet a shorter real column.
loads = [4, 4, 2, 7, 5]
stack indexes before 7 arrives: [0, 1, 2]
pop 2 -> answer[2] = 7
pop 1 -> answer[1] = 7
pop 0 -> answer[0] = 7
remaining unresolved: indexes 3 and 4
answer = [7, 7, 7, -1, -1]
The two loads of four both remain unresolved when the second four arrives, because the task requires a strictly larger value. The following two is smaller and also remains on the stack. When seven arrives, it resolves all three positions. None saw a qualifying earlier future value, or it would already have left the stack. The final five can't resolve seven, and neither has a later larger load, so their default answers stay minus one. Although seven triggers three pops in one iteration, those indexes can never be popped again. Across the whole scan, there are only n pushes and at most n pops.