Algorithm patterns← All patterns

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.

time O(n)space O(n)

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.

Example 1

Input: temperatures = [73, 74, 75, 71, 69, 72, 76, 73]

Output: [1, 1, 4, 2, 1, 1, 0, 0]

Example 2

Input: temperatures = [30, 40, 50, 60]

Output: [1, 1, 1, 0]

Example 3

Input: temperatures = [30, 60, 90]

Output: [1, 1, 0]

WALKTHROUGH INPUT · temperatures = [73, 74, 75, 71, 69, 72, 76, 73]

temperatures

73
0
74
1
75
2
71
3
69
4
72
5
76
6
73
7
stack

answer (days to wait)

·
0
·
1
·
2
·
3
·
4
·
5
·
6
·
7

The stack holds days still waiting for a warmer one. Their temps only go down.

1 / 16
solution.ts
1function dailyTemperatures(temps: number[]): number[] {
2 const answer = new Array(temps.length).fill(0);
3 const stack: number[] = []; // indices, temps going down
4 for (let i = 0; i < temps.length; i++) {
5 while (stack.length && temps[i] > temps[stack.at(-1)!]) {
6 const j = stack.pop()!;
7 answer[j] = i - j;
8 }
9 stack.push(i);
10 }
11 return answer;
12}

Practice next