Stacks and heaps · Intermediate
Monotonic stack
Keep a stack whose values only increase (or only decrease); each new element pops everything it beats, answering "next greater" for all of them at once.
On this page
The idea
For each element you want the nearest element to its right (or left) that is larger, or smaller. Scanning right from every element is quadratic. Instead, keep the indices still waiting for an answer on a stack. Their values are decreasing from bottom to top, because a larger value would already have answered the smaller ones below it.
When a new value arrives, it is the answer for every waiting index whose value is smaller, and those are exactly the ones on top. Pop them, record the answer, then push the new index. The monotonic deque is the same idea with removals from the front, used for sliding-window maximums.
How to recognise it
- "Next greater", "next smaller", "previous warmer day", "how many days until"…
- For each element, the answer is the nearest element in one direction that beats it.
- Spans, visible buildings, histogram areas: anything bounded by the first larger or smaller neighbour.
When not to use it
- You need the k-th greater element or a global order statistic: a heap or sorting fits better.
- The comparison is not a total order on single values (for example two-dimensional dominance).
Template
Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.
# For each i, distance to the next strictly greater value (0 if none)
answer = [0] * n
stack = [] # indices; values decrease from bottom to top
for i in range(n):
while stack and a[stack.top()] < a[i]:
j = stack.pop()
answer[j] = i - j # a[i] is the first greater value after j
stack.push(i)
return answer # indices left on the stack have no greater value- Store indices, not values: you usually need the distance or position.
- Strict versus non-strict comparison decides how equal values are treated; pick it from the problem statement.
Complexity
Time O(n), extra space O(n). Each index is pushed once and popped at most once, so the inner while loop runs at most n times over the whole scan.
Worked examples
Temperatures [30, 28, 31, 29, 33]
Push 0 (30), push 1 (28). 31 arrives: pops 1 (answer 1) and 0 (answer 2), then push 2. Push 3 (29). 33 arrives: pops 3 (answer 1) and 2 (answer 2). Index 4 never finds a warmer day: answer 0.
Pitfalls
- Comparing with the wrong sign and building an increasing stack when you needed a decreasing one.
- Forgetting the elements left on the stack at the end (they need a default answer).
Practise it
Solved problems with hints, a correctness argument and four tested implementations:
- ProblemHow many days until it gets warmer?· intermediate · O(n)
- ProblemNext bigger value on a ring· intermediate · O(n)
Learn the foundations
Lessons
- ModuleM08 Stacks· beginner
- ModuleM09 Queues and Deques· beginner
- VisualizerStack· push/pop amortized O(1)
- CollectionArrayDeque<E>· Java
- Collectionlist· Python
Related patterns
- PatternSliding window· O(n)
References
dsa.pattern.monotonic-stack · version 1