The problem
For each number, find the first larger number to its right, or -1 if there is none. The bottom row shows the goal. Checking every later number takes up to n(n-1)/2 comparisons: 15 for six numbers, so O(n²).
The fast way walks the list once with a stack of indices still waiting for an answer. Their values only fall from bottom to top, so the stack is monotonic: it only ever goes one way. ans starts as all -1.
One pass with a stack
i = 0, x = 2. The stack is empty, so there is nothing to compare. Push index 0: the number 2 now waits for something bigger.
i = 1, x = 7. The top waits on 2, and 2 < 7, so 7 is the first bigger number after 2: pop index 0 and write ans[0] = 7. The stack is now empty, so push index 1.
x = 3 is smaller than 7, and x = 1 is smaller than 3, so neither answers anyone. Push index 2, then index 3. The values on the stack, 7, 3, 1, still fall.
i = 4, x = 5. Pop index 3 (1 < 5): ans[3] = 5. Pop index 2 (3 < 5): ans[2] = 5. The top now holds 7, which is not smaller, so stop and push index 4.
i = 5, x = 4. The top holds 5, and 5 is not smaller than 4, so nothing pops. Push index 5. The stack holds 7, 5, 4: still falling.
The loop ends. Indices 1, 4 and 5 are still waiting: no bigger number came after 7, 5, 4. Their answers stay -1, so ans = [7, -1, 5, 5, -1, -1].
Cost, then a queue
The while loop sits inside the for loop, yet each index is pushed once and popped at most once. Here: 6 pushes and 3 pops. With n numbers that is at most 2n stack operations, so the whole pass is O(n).
Sliding window maximum: the largest number in each window of k = 3. A deque (double-ended queue) pops smaller or equal values from the back, so its front holds the maximum. out[0] = 7, written under a[2], its window's last index.
Slide right. 1 waits behind 3. Then 5 pops 1 and 3 from the back, and index 1 (the 7) is outside the window, so popleft removes it. out = [7, 7, 5, 5]. Each index enters once and leaves at most once: O(n).
What happens
;; step 1/11 · problem a = [2, 7, 3, 1, 5, 4] goal [7, -1, 5, 5, -1, -1] brute force: for each i, scan a[i+1:] for the first bigger number on this list: 9 comparisons on a falling list of 6: 5 + 4 + 3 + 2 + 1 = 15 in general n(n-1)/2, which is O(n²)
The stack holds indices, not values, so a pop knows which answer to fill in: ans[st.pop()] = x. Each block in the figure shows its index on top and its value below. window_max returns 4 maxima for 6 numbers (n - k + 1). In the figure each one is written under the last index of its window, so out[0] sits under a[2] and out[3] under a[5]; the cells under a[0] and a[1] stay empty. The O(n) bound is an aggregate count, as in CLRS chapter 16 (the stack with MULTIPOP): every pop removes something an earlier push added, so over the whole run there are at most as many pops as pushes. One iteration of the for loop can still pop many times.