Daily Temperatures Visualizer & Step-by-Step Algorithm Solution

Find the number of days you have to wait after the i-th day to get a warmer temperature using a monotonic decreasing stack.

Category: stack | Difficulty: Medium

Tags: Monotonic Stack, Array

Daily Temperatures

Temperatures
73
0
74
1
75
2
71
3
69
4
72
5
76
6
73
7
Result (Wait Days)
0
0
0
1
0
2
0
3
0
4
0
5
0
6
0
7
Push / Pop (Top)
(Empty Stack)
Monotonic Stack (Indices)
100%
state
iN/A
currentTempN/A
stack.length0
Initialization
1/41
Explanation

Initialize empty monotonic stack to store indices.

Source Code
1function dailyTemperatures(temperatures) {
2 const stack = [];
3 const result = new Array(temperatures.length).fill(0);
4 for (let i = 0; i < temperatures.length; i++) {
5 const currentTemp = temperatures[i];
6 while (stack.length && temperatures[stack[stack.length - 1]] < currentTemp) {
7 const prevIdx = stack.pop();
8 result[prevIdx] = i - prevIdx;
9 }
10 stack.push(i);
11 }
12 return result;
13}