Monotonic stack
Keep a stack whose values only increase (or only decrease) from bottom to top. When a new value breaks the order, pop. Each popped value has just met its next greater (or smaller) value. Every index is pushed and popped once, so the scan is O(n).
How to recognise it
- For every element you need the next or previous greater or smaller element.
- You must find how far each value stays the maximum or minimum: spans, ranges or rectangles.
- A greedy choice is undone when a better value arrives: remove digits, collisions.
The picture
Think of people in a line looking right. Each one waits until someone taller arrives. The ones still waiting are in decreasing height from bottom to top: a taller one would already have answered the shorter ones before it.
answer = [-1] * n
stack = [] # indexes still waiting
for i from 0 to n - 1:
while stack and a[top] < a[i]:
answer[pop] = a[i] # a[i] is their next greater
push i
Four variants
| You want | Pop while the top is | Direction of scan |
|---|---|---|
| next greater | smaller than the new value | left to right |
| next smaller | bigger than the new value | left to right |
| previous greater | not greater than the new value | left to right, read the top after popping |
| previous smaller | not smaller than the new value | left to right, read the top after popping |
You can also scan right to left and read the top after popping to get the "next" answers.
Contributions
When a value is popped, the new top is its nearest smaller (or greater) value on the left, and the current index is its
nearest on the right. So the value is the minimum (or maximum) of left × right subarrays, and is the shortest bar of a
rectangle that spans everything between. This one idea solves sum of subarray minimums, subarray ranges and the
largest rectangle.
With equal values, use a strict comparison on one side and a non-strict one on the other, so that each subarray is counted once.
Common mistakes
- Pushing values when you need widths: push indexes.
- Forgetting to flush the stack at the end (a sentinel 0 or
-∞makes that automatic). - Counting equal values twice on both sides.
Problems
- Next Greater Element Ieasyguide ready
- Next Greater Element IImediumguide ready
- Asteroid Collisionmediumguide ready
- Sum of Subarray Minimumsmediumguide ready
- Sum of Subarray Rangesmediumguide ready
- Remove K Digitsmediumguide ready
- Online Stock Spanmediumguide ready
- Next Smaller Elementmediumguide ready
- Largest Rectangle in Histogramhardguide ready
- Maximal Rectanglehardguide ready