Lesson 130 of 296
Monotonic stack
What you will learn
- What "monotonic" means
- The next greater element pattern
- Daily Temperatures
- Next Greater Element
- Largest Rectangle in Histogram
On this page
The idea
A monotonic stack keeps its items in sorted order (always increasing or always decreasing from bottom to top). Before pushing a new item, you pop every item that breaks the order. The moment an item is popped is exactly when you have found its next greater (or next smaller) element.
Use it for questions like:
- "For each day, how many days until a warmer temperature?"
- "For each item, the next item to the right that is bigger."
Brute force for these is O(n²). A monotonic stack does it in O(n), because every index is pushed once and popped at most once.
Daily Temperatures
Problem (LeetCode 739): for each day, the number of days until a warmer temperature (0 if never).[73, 74, 75, 71, 69, 72, 76, 73] → [1, 1, 4, 2, 1, 1, 0, 0].
Idea: keep a stack of indexes of days still waiting for a warmer day. Their temperatures are decreasing from bottom to top. When today is warmer than the day on top, that day has found its answer: pop it and record the distance. Repeat, then push today.
function dailyTemperatures(temps: number[]): number[] {
const answer = new Array<number>(temps.length).fill(0);
const waiting: number[] = [];
for (let today = 0; today < temps.length; today++) {
while (waiting.length > 0 && temps[today]! > temps[waiting.at(-1)!]!) {
const earlier = waiting.pop()!;
answer[earlier] = today - earlier;
}
waiting.push(today);
}
return answer;
}Trace the start:
| today | temp | pops (answers) | waiting after |
|---|---|---|---|
| 0 | 73 | none | [0] |
| 1 | 74 | day 0 → 1 | [1] |
| 2 | 75 | day 1 → 1 | [2] |
| 3 | 71 | none | [2, 3] |
| 4 | 69 | none | [2, 3, 4] |
| 5 | 72 | day 4 → 1, day 3 → 2 | [2, 5] |
| 6 | 76 | day 5 → 1, day 2 → 4 | [6] |
Days left in the stack at the end never found a warmer day, so their answer stays 0.
O(n) time, O(n) space. Store indexes, not values: you need the positions to calculate distances.
Next Greater Element (array version)
For each item, the next greater item to its right, or -1.[2, 1, 2, 4, 3] → [4, 2, 4, -1, -1].
function nextGreaterElements(nums: number[]): number[] {
const result = new Array<number>(nums.length).fill(-1);
const stack: number[] = [];
for (let i = 0; i < nums.length; i++) {
while (stack.length > 0 && nums[i]! > nums[stack.at(-1)!]!) {
result[stack.pop()!] = nums[i]!;
}
stack.push(i);
}
return result;
}(For a circular array, LeetCode 503, loop twice through the indexes using i % n.)
Largest Rectangle in Histogram (stretch)
Problem (LeetCode 84, hard): bar heights; find the area of the largest rectangle that fits inside the histogram.[2, 1, 5, 6, 2, 3] → 10 (heights 5 and 6, width 2, height 5).
Idea: keep an increasing stack of indexes. When a shorter bar arrives, the bars popped from the stack cannot extend further right. For each popped bar, its rectangle's height is its own height, and its width runs from just after the new stack top to just before the current index.
function largestRectangleArea(heights: number[]): number {
const stack: number[] = [];
let best = 0;
for (let i = 0; i <= heights.length; i++) {
const current = i === heights.length ? 0 : heights[i]!;
while (stack.length > 0 && current < heights[stack.at(-1)!]!) {
const height = heights[stack.pop()!]!;
const leftBoundary = stack.length > 0 ? stack.at(-1)! : -1;
const width = i - leftBoundary - 1;
best = Math.max(best, height * width);
}
stack.push(i);
}
return best;
}The extra loop step with height 0 at the end flushes every remaining bar. O(n) time.
Choosing increasing or decreasing
| Looking for | Keep the stack |
|---|---|
| Next greater element | Decreasing (pop while current is greater) |
| Next smaller element | Increasing (pop while current is smaller) |
How to say it in an interview
"A monotonic stack keeps indexes whose values are in sorted order. For next-greater problems I keep a decreasing stack and, when a larger value arrives, pop everything smaller, recording the current index as their answer. Each index is pushed and popped at most once, so Daily Temperatures is O(n) instead of O(n squared). For Largest Rectangle in Histogram I keep an increasing stack and compute each popped bar's width from the new stack top to the current index."
Key words
| Word | Meaning |
|---|---|
| Monotonic | Always increasing or always decreasing |
| Monotonic stack | A stack kept in sorted order by popping first |
| Next greater element | The first larger item to the right |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.