Pattern 09 / 10 · Advanced
Monotonic Stack
Keep a stack in sorted order; whatever gets popped has just found its answer.
The idea
Walk left to right with a stack of indices whose values only go down. A new value that is bigger than the top is the answer for that top, so pop it and record the distance. Each index is pushed and popped once.
Reach for it when
- For each item you need the next (or previous) greater or smaller item.
- Spans, stock prices, temperatures, histogram rectangles.
- A nested loop scans forward from every index looking for a bigger value.
Watch it run
739. Daily Temperatures
For each day, return how many days you wait for a warmer temperature, or 0 if none comes.
Input: temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1, 1, 4, 2, 1, 1, 0, 0]
Input: temperatures = [30, 40, 50, 60]
Output: [1, 1, 1, 0]
Input: temperatures = [30, 60, 90]
Output: [1, 1, 0]
WALKTHROUGH INPUT · temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
temperatures
answer (days to wait)
The stack holds days still waiting for a warmer one. Their temps only go down.
1function dailyTemperatures(temps: number[]): number[] {2const answer = new Array(temps.length).fill(0);3const stack: number[] = []; // indices, temps going down4for (let i = 0; i < temps.length; i++) {5while (stack.length && temps[i] > temps[stack.at(-1)!]) {6const j = stack.pop()!;7answer[j] = i - j;8}9stack.push(i);10}11return answer;12}