A monotonic stack is an ordinary stack that you keep sorted (increasing or decreasing) by popping anything that would break the order before you push. Each pop answers a question about the popped element, such as "what is the next greater value to my right?". Because every element is pushed once and popped at most once, a whole family of seemingly O(n²) problems drops to O(n). The double-ended version, the monotonic deque, does the same for sliding-window maximum and minimum.
Think of it like
Buildings waiting for a taller neighbor
Walk down a street from left to right, looking for the first taller building to the right of each one. Keep a stack of buildings still waiting for an answer. When a tall building appears, every shorter building on top of the stack gets its answer and leaves. The buildings still waiting are always in decreasing order of height, because any shorter building behind a taller one would already have been answered.
How to recognize it
- "Next greater / next smaller element", "previous greater / smaller", "how many days until a warmer temperature".
- "For each element, how far does it extend" as the minimum or maximum of a range (stock span, histogram bars, visible people).
- Area or water problems bounded by the nearest taller or shorter bar on each side.
- Sums or counts over all subarrays of their min or max (the contribution technique).
- Maximum or minimum of every window of size k: use a monotonic deque.
- Build the lexicographically smallest result by deleting characters or digits (Remove K Digits).
The core idea
Scan left to right and keep a stack of indices whose answer is not known yet. When the new value x arrives, it is the answer for every waiting element it beats, so pop those and record x for them. Then push the current index, because its own answer is still unknown.
def next_greater(a):
ans = [-1] * len(a) # -1 = no greater element to the right
stack = [] # indices; their values decrease from bottom to top
for i, x in enumerate(a):
while stack and a[stack[-1]] < x:
ans[stack.pop()] = x # x is the first greater value for the popped index
stack.append(i)
return ans| i | temp | Popped (answer = days waited) | Stack after (indices) |
|---|---|---|---|
| 0 | 73 | [0] | |
| 1 | 74 | 0 → 1 day | [1] |
| 2 | 75 | 1 → 1 day | [2] |
| 3 | 71 | [2, 3] | |
| 4 | 69 | [2, 3, 4] | |
| 5 | 72 | 4 → 1 day, 3 → 2 days | [2, 5] |
| 6 | 76 | 5 → 1 day, 2 → 4 days | [6] |
| 7 | 73 | [6, 7] |
[73, 74, 75, 71, 69, 72, 76, 73]. Indices left on the stack never see a warmer day, so their answer is 0. Result: [1, 1, 4, 2, 1, 1, 0, 0].The four variants
| Question | Stack order (bottom → top) | Pop while | Answer recorded |
|---|---|---|---|
| Next greater | Decreasing | a[top] < x | For each popped index: x |
| Next smaller | Increasing | a[top] > x | For each popped index: x |
| Previous greater | Decreasing | a[top] <= x | For the current index: the top after popping |
| Previous smaller | Increasing | a[top] >= x | For the current index: the top after popping |
Largest rectangle in histogram
The best rectangle that uses bar i as its shortest bar stretches left to just after the previous smaller bar and right to just before the next smaller bar. An increasing stack finds both boundaries at the moment bar i is popped.
- 1
Keep the stack increasing
Bars on the stack are waiting for a shorter bar to their right.
- 2
Pop on a shorter bar
When
h[i] < h[top], poptop. Bariis its next smaller bar (the right boundary). - 3
Read the left boundary
After popping, the new top is the previous smaller bar. Width =
i - newTop - 1(oriif the stack is empty). - 4
Flush with a sentinel
Append a bar of height 0 at the end so every remaining bar is popped and measured.
For heights [2, 1, 5, 6, 2, 3], the bar of height 2 at index 4 pops 6 (area 6 × 1) and then 5 (area 5 × 2 = 10, the answer). Maximal Rectangle in a binary matrix applies this row by row, treating each row as the base of a histogram.
i. The dashed green outline is the best so far, and the sentinel 0 at the end flushes the bars still waiting.Trapping rain water
With a decreasing stack, water is trapped whenever a taller bar arrives: pop the bottom of the "valley", then the new top is the left wall and the current bar is the right wall. Add width × (min(leftWall, rightWall) - bottom), where width = i - left - 1. The stack fills water layer by layer, horizontally.
Prefix max arrays
- Water at i =
min(maxLeft[i], maxRight[i]) - h[i] - O(n) time, O(n) space
- Easiest to explain
Monotonic stack
- Fills water in horizontal layers
- O(n) time, O(n) space
- Generalizes to other "bounded by nearest taller" problems
Two pointers
- Move the side with the smaller max inward
- O(n) time, O(1) space
- See Two Pointers
Sum of subarray minimums: the contribution technique
Instead of enumerating all O(n²) subarrays, ask how many subarrays have a[i] as their minimum. If left[i] is the distance to the previous smaller element and right[i] is the distance to the next smaller element, then a[i] is the minimum of exactly left[i] × right[i] subarrays.
| i | a[i] | left (to previous smaller) | right (to next smaller-or-equal) | Contribution |
|---|---|---|---|---|
| 0 | 3 | 1 | 1 | 3 |
| 1 | 1 | 2 | 3 | 6 |
| 2 | 2 | 1 | 2 | 4 |
| 3 | 4 | 1 | 1 | 4 |
[3, 1, 2, 4] gives 3 + 6 + 4 + 4 = 17.def sum_subarray_mins(a: list[int]) -> int:
MOD = 10**9 + 7
n = len(a)
left, right = [0] * n, [0] * n
stack: list[int] = []
for i in range(n):
while stack and a[stack[-1]] >= a[i]:
right[stack.pop()] = i # next smaller-or-equal is i
left[i] = i - (stack[-1] if stack else -1) # previous strictly smaller
stack.append(i)
for j in stack:
right[j] = n # nothing smaller to the right
return sum(a[i] * left[i] * (right[i] - i) for i in range(n)) % MODMonotonic deque: sliding window maximum
To get the maximum of every window of size k, keep a deque of indices whose values decrease from front to back. A new value evicts every smaller value from the back (they can never be a window maximum again, because the newcomer is larger and will outlive them). The front is evicted when it slides out of the window. The front is always the current maximum.
| i | x | Deque after (values) | Window max |
|---|---|---|---|
| 0 | 1 | [1] | |
| 1 | 3 | [3] (1 evicted) | |
| 2 | −1 | [3, -1] | 3 |
| 3 | −3 | [3, -1, -3] | 3 |
| 4 | 5 | [5] (all evicted) | 5 |
| 5 | 3 | [5, 3] | 5 |
| 6 | 6 | [6] | 6 |
| 7 | 7 | [7] | 7 |
[1, 3, -1, -3, 5, 3, 6, 7] with k = 3 gives [3, 3, 5, 5, 6, 7].Why it is O(n): the amortized argument
The inner while loop can pop many elements in one iteration, so a single step may cost O(n). But every index is pushed exactly once and popped at most once over the entire run, so the total number of pops is at most n. Total work is at most 2n stack operations plus n comparisons that end a while loop: O(n).
Choosing a tool
| Need | Tool | Time |
|---|---|---|
| Next / previous greater or smaller for every element | Monotonic stack | O(n) |
| Max or min of every window of size k | Monotonic deque | O(n) |
| Max of a dynamic set with arbitrary deletions | Heaps & Priority Queues with lazy deletion | O(n log n) |
| Arbitrary range-min queries | Sparse table or Segment Trees | O(1) or O(log n) per query |
| Brute force for each element | Nested loops | O(n²) |
Complexity
| Problem | Time | Space | Notes |
|---|---|---|---|
| Next greater / smaller element | O(n) | O(n) | Each index pushed and popped once |
| Daily temperatures | O(n) | O(n) | Answer = index difference |
| Largest rectangle in histogram | O(n) | O(n) | Sentinel 0 flushes the stack |
| Trapping rain water (stack) | O(n) | O(n) | Two pointers achieves O(1) space |
| Sum of subarray minimums | O(n) | O(n) | Contribution technique |
| Sliding window maximum | O(n) | O(k) | Monotonic deque |
All bounds are amortized: a single step may pop many elements, but the total number of pops never exceeds n.
Implementation
A decreasing stack of indices; each pop records how long that day waited for a warmer one.
def daily_temperatures(temps: list[int]) -> list[int]:
ans = [0] * len(temps)
stack: list[int] = [] # indices with decreasing temperatures
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
j = stack.pop()
ans[j] = i - j # day j waited i - j days
stack.append(i)
return ansKey takeaways
- A monotonic stack keeps indices in sorted value order; each pop answers "next greater/smaller" for the popped element.
- Every index is pushed once and popped at most once, so the total work is O(n) even though one step may pop many items.
- Largest rectangle and trapping rain water read both boundaries (previous and next smaller or taller) at pop time.
- The contribution technique sums
a[i] × left[i] × right[i]; break ties strictly on one side only. - A monotonic deque gives the max or min of every sliding window in O(n).
Common pitfalls
- Pushing values instead of indices, which loses distances and confuses duplicates.
- Using the same strictness on both sides in contribution problems, which double counts or misses equal elements.
- Forgetting the sentinel (or a final flush) so bars left on the stack are never measured.
- Evicting the deque front with the wrong window check (
<= i - kis the correct test for an index that left). - Claiming O(n²) because of the nested loop instead of giving the amortized argument.
Interview tips
- When a brute force looks like "for each element, scan right until something bigger", say "monotonic stack" immediately.
- State the stack order and what a pop means before writing code.
- For trapping rain water, know all three solutions and lead with two pointers if O(1) space is requested.
Real-world applications
- Stock analysis: price spans and next higher close.
- Skyline and visibility computations in graphics and city planning.
- Streaming max/min over time windows in monitoring systems.
- Optimizing DP transitions over sliding ranges (deque optimization).
Practice problems
Test yourself
Why does the next-greater-element algorithm run in O(n) despite the nested while loop?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.