Monotonic Stack
A stack kept in sorted order to find the next greater or smaller element.
- visited / done
- active this step
- result
- removed / popped
Each day is warmer than the last
74 pops 73 (1 day), and 75 pops 74 (1 day). The stack holds 75’s index.
VARIABLES
- i
- 2
- stack
- [2]
- answer
- [1, 1, 0, 0, 0, 0, 0]
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Push indices onto a stack while keeping their values decreasing (or increasing). A new element pops every smaller one - and is their “next greater” answer.
Why it matters
Each index is pushed and popped once, so “next greater for every element” is O(n) instead of O(n²).
Think of it like this
People in a line looking right: a tall person arriving blocks the view of everyone shorter before them.
Use it when
- Next greater or next smaller element
- Span and “days until warmer” questions
- Largest rectangle in a histogram
Avoid it when
- You need each window’s maximum - use a monotonic queue
- No “nearest bigger or smaller” relationship in the problem
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Monotonic stack pass | O(n) | O(n) |
| Scan right from each element | O(n²) | O(1) |
| Each push or pop | O(1) | - |
Often confused with: monotonic queues - they also drop items from the front as a window moves on.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- Store indices, not values - you usually need distances
- Indices left on the stack at the end have no answer
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Storing values instead of indices, which loses the distance
- Using <= where < is needed when values are equal
- Forgetting that indices left on the stack keep the default answer
Edge cases to test
- Strictly decreasing input - nothing ever pops
- All values equal
- A single element
Knowledge check
Quick check to lock in the intuition.
Why is a monotonic stack O(n) even with a while loop inside the for loop?
Practice
Apply what you just watched on real interview problems.