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.
days until warmer
stack (index: temperature)
1def daily_temperatures(t):2 ans = [0] * len(t)3 stack = [] # indices, temperatures decreasing4 for i, x in enumerate(t):5 while stack and t[stack[-1]] < x:6 j = stack.pop()7 ans[j] = i - j8 stack.append(i)9 return ans
Variables
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
Stacks & queues
A stack gives back the most recent item first (LIFO); a queue gives back the oldest first (FIFO). Both do push and pop in O(1). Nested structure → stack. Processing in order of arrival → queue.
7 min read →Sliding window
For questions about a contiguous subarray or substring, keep a window: grow it on the right, and shrink it from the left only when it breaks the rule. Each element enters and leaves once: O(n) instead of checking all O(n²) ranges.
9 min read →