Algorithms Playbook
PatternTime O(n) · Space O(n)8 min read

Monotonic stack: the next greater element in one pass

A stack that keeps its items sorted, popping the ones that can no longer be the answer. It turns "next greater / smaller element" problems from O(n²) into O(n).

In short

Keep a stack of items still waiting for an answer, in sorted order. When a new item resolves some of them, pop and answer. Each item is pushed and popped once: O(n).

The idea: who's still waiting?

For each day, how many days until a warmer one? The brute force looks ahead from every day (O(n²)). Flip it around: when a warm day arrives, it answers every colder day that was waiting. Keep the waiting days on a stack; they're always in decreasing temperature order, because a colder day after a warmer one would be answered first.

Monotonic stack: days until a warmer temperature
Temperatures
Speed
073174275371469572676773

days until warmer

0010203040506070

stack (index: temperature)

1def daily_temperatures(t):
2 ans = [0] * len(t)
3 stack = [] # indices, temperatures decreasing
4 for i, x in enumerate(t):
5 while stack and t[stack[-1]] < x:
6 j = stack.pop()
7 ans[j] = i - j
8 stack.append(i)
9 return ans
For each day, how many days until a warmer one? The stack will hold days still waiting for their answer.

Variables

i—
Step 1/24· Pops: 0
A monotonic stack keeps its elements sorted. Each element is pushed once and popped once, so the nested-looking loop is O(n).

The template

stack = []                      # indices, still waiting
for i, x in enumerate(a):
    while stack and a[stack[-1]] < x:   # x answers them
        j = stack.pop()
        answer[j] = i - j
    stack.append(i)
  • Flip the comparison for next smaller elements.
  • Iterate right to left for previous greater/smaller.
  • Store indices when you need distances, values when you only need the value.

How to recognise it

  • "Next greater / smaller element", "days until warmer", "stock span".
  • Largest rectangle in a histogram and "trapping rain water" (a stack version).
  • A brute force that looks ahead (or behind) from every position until a condition is met.

Key takeaways

  • 01A monotonic stack holds items still waiting, sorted.
  • 02A new item pops everything it resolves, then is pushed.
  • 03Each item is pushed and popped once: O(n) overall.
  • 04Spot it from "next greater / smaller" wording.

Check your understanding

1 of 3

What does the stack hold in "days until warmer"?

Related topics