1def next_greater(a):2 ans = [-1] * len(a)3 st = []4 for i, x in enumerate(a):5 while st and a[st[-1]] < x:6 ans[st.pop()] = x7 st.append(i)8 return ans1from collections import deque2def window_max(a, k):3 dq, out = deque(), []4 for i, x in enumerate(a):5 while dq and a[dq[-1]] <= x:6 dq.pop()7 dq.append(i)8 if dq[0] <= i - k:9 dq.popleft()10 if i >= k - 1:11 out.append(a[dq[0]])12 return out[0]2[1]7[2]3[3]1[4]5[5]4abottomtop[0]7[1]-1[2]5[3]5[4]-1[5]-1answindow k = 3[0]2[1]7[2]3[3]1[4]5[5]4[0]2[1]7[2]3[3]1[4]5[5]4
Code card: the function running; the highlighted line is the one being runBlocks: an index (top) and its value (bottom)Tray: the stack (bottom → top), later the deque (front → back)Back row: the list a · front row: the answersThe list a = [2, 7, 3, 1, 5, 4] sits in the back row. Each index block hops onto the tray, a stack whose values fall from bottom to top. A bigger number pops every smaller block off the top; each popped block flies to its answer cell, which takes the bigger number. With a window of 3, the same tray is a deque: the back rule is the same, and the front block leaves once its index slides out of the window, so the front is always the window's maximum.

The problem

  1. 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²).

One pass with a stack

Cost, then a queue

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.