Monotonic Stack
A monotonic stack is a regular stack with one extra rule: it always stays in sorted order — either always increasing from bottom to top, or always decreasing.
To keep the order, whenever you push a new element, you first pop everything that would break the order. This is the key trick.
Next Greater Element — the classic problem
Given an array like [2, 1, 5, 3, 6], find for each element the next element to its right that is greater than it.
- For 2 → next greater is 5
- For 1 → next greater is 5
- For 5 → next greater is 6
- For 3 → next greater is 6
- For 6 → none
A naive approach checks every pair: \(O(n^2)\). A monotonic stack does it in \(O(n)\).
← → arrow keys to step · click elements to interact
How the algorithm works
Walk through the array left to right. Maintain a decreasing monotonic stack (largest at bottom, smallest at top):
- For each element
x, pop elements from the stack while the top is smaller than x. - Each popped element has found its next greater element: it's
x! - Push
xonto the stack.
Because each element is pushed once and popped at most once, the total work is \(O(n)\). Every element is processed exactly twice.
Other patterns
Monotonic stacks solve many problems (the monotonic queue variant handles sliding window max/min):
- Next Smaller Element — use an increasing stack
- Largest Rectangle in Histogram — maintain heights in increasing order
- Trapping Rain Water — two-pass monotonic stack
- Daily Temperatures — classic next greater element variant