FAANGPrep Sprint
Daily Temperatures
Find how many days you have to wait for a warmer temperature.
MediumSolve on LeetCode
Problem Understanding
temperatures[i] is the temperature on day i. Build an array answer where answer[i] counts the days from day i until the first strictly warmer day. If no warmer day ever comes, answer[i] stays 0.
Algorithm Strategy
We use a Monotonic Decreasing Stack.
- Initialize
answerarray with 0s. - Use a stack to store indices of days.
- Iterate through
temperatures. - While the current temperature is warmer than the temperature at the index stored in
stack.top():- We found a warmer day for
stack.top()! - Pop the index (
prevIndex). - Calculate days waiting:
i - prevIndex. - Update
answer[prevIndex].
- We found a warmer day for
- Push current index
ionto the stack.
Interactive Visualization
8 DAYS
ANSWER = 0
temperatures · answer
73
0
0
74
0
1
75
0
2
71
0
3
69
0
4
72
0
5
76
0
6
73
0
7
stack · waiting days
empty
Waiting
0
Answered
0
answer starts as zeros: a day with no warmer day after it keeps 0
Next
Day 0: 73°
Temps
Visualize how the monotonic stack keeps track of 'unresolved' cooler days.
