Daily Temperatures
MediumNeetCode 150 StackDisneyAgodaZohoGrabProblem
You get temperatures, the temperature recorded on each day. For every day, work out how many
days you would have to wait to see a strictly warmer temperature.
Return an array answer where answer[i] is that wait for day i.
If no later day is warmer, answer[i] is 0.
Constraints
- 1 ≤ temperatures.length ≤ 100000
- 30 ≤ temperatures[i] ≤ 100
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(n)
Time: Each day is pushed once and popped at most once, so the inner loop does at most n pops in total.
Space: The stack can hold every day when temperatures keep falling, plus the answer array.
Keep a stack of days that are still waiting, with colder days on top. When a new day is warmer than the top, that top day's wait is over: pop it and record the distance. Then push the new day.