Pattern #09
Monotonic Stack
RecommendedNext greater/smaller, histogram rectangles, and temperature waits.
When to use
For each index you need the nearest stricter greater/smaller on the left or right, or a span until a barrier.
Recognition cues
- Next greater / next smaller element
- Daily temperatures / online stock span
- Largest rectangle in histogram
Common pitfalls
- Strict vs non-strict comparison (affects duplicates)
- Storing values instead of indices when you need distance
- Forgetting left and right barriers for histogram
90-second recognition drill
Which pattern fits best?
- Next greater / next smaller element
- Daily temperatures / online stock span
- Largest rectangle in histogram
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
Step 1 of 9
73
074
175
271
369
472
576
673
7stack
∅
Statei=-stack=[]
How to think about it
Keep a stack of indices whose values are monotone (increasing or decreasing). When a new value breaks the order, pop and resolve those indices: the newcomer is their next greater/smaller. Each index is pushed and popped at most once.
Template shapes
| Shape | Core move | Example |
|---|---|---|
| Histogram | Increasing stack of indices. A lower bar, or a virtual height 0 at the end, pops. Area is height * (right - left - 1), with right = i and left the new top, or -1 |
LC 84 |
| Histogram per row | A '1' grows the bar and a '0' resets it to 0. Each row then uses the LC 84 stack |
LC 85 |
| Next greater | Decreasing stack. Pop while the current value is greater. The answer is that value, not a distance | LC 496 |
| Circular next greater | The same decreasing stack over 2n steps, with index k % n. Push only while k < n, so each index is pending once |
LC 503 |
| Warmer day | Decreasing temperatures. When today is warmer than the top, answer[top] = i - top |
LC 739 |
| Subarray minimums | left[i] reaches the previous smaller-or-equal. right[i] reaches the next strictly smaller. Add arr[i] * left[i] * right[i], modulo 10^9+7 |
LC 907 |
Complexity baseline
O(n) time (amortized one push/pop per index), O(n) stack space.
From template to problem
- Store indices. The answer is a distance, a width, or a value looked up at that index.
- Next greater pops a decreasing stack (LC 496, LC 739). Nearest smaller pops an increasing stack (LC 84).
- Duplicates care about strictness. LC 907’s left bound is smaller-or-equal and its right bound is strictly smaller.
- A circular next-greater walks
2nsteps and pushes only whilek < n(LC 503). Unresolved indexes stay -1.
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
Monotonic Stack · Template
/** Monotonic stack template: next greater element to the right (−1 if none). */
export function nextGreater(nums: number[]): number[] {
const n = nums.length;
const ans = new Array<number>(n).fill(-1);
const stack: number[] = [];
for (let i = 0; i < n; i++) {
while (stack.length && nums[stack.at(-1)!]! < nums[i]!) {
ans[stack.pop()!] = nums[i]!;
}
stack.push(i);
}
return ans;
}
/** Monotonic stack template: next greater element to the right (−1 if none). */
export function nextGreater(nums: number[]): number[] {
const n = nums.length;
const ans = new Array<number>(n).fill(-1);
const stack: number[] = [];
for (let i = 0; i < n; i++) {
while (stack.length && nums[stack.at(-1)!]! < nums[i]!) {
ans[stack.pop()!] = nums[i]!;
}
stack.push(i);
}
return ans;
}
#StatusProblemTypeDifficultyDone
- 1#84 Largest Rectangle in HistogramGuidehard
- 2#85 Maximal RectangleGuidehard
- 3#496 Next Greater Element IGuideeasy
- 4#503 Next Greater Element IIGuidemedium
- 5#739 Daily TemperaturesGuidemedium
- 6#907 Sum of Subarray MinimumsGuidemedium