mediumStackAmazonGoogleBloomberg
Warmer Day Countdown
For each day's temperature reading, report how many days you must wait before a warmer day arrives (0 if none).
Given `temps`, return `ans[i]` = number of days after i until a strictly warmer day, or 0 if there is none.
Choose approach
Input
73
74
75
71
69
72
76
73
top
1/16
Narrationstep 1 of 16
Monotonic decreasing stack of indices. When day i is warmer than the top, the top's wait is resolved.
Variables
i=0
How to think about it
- Brute force compares every (i, j) → O(n²).
- Insight: once day j finds a warmer day, we never need j again.
- Keep days without a warmer successor on a stack (decreasing by temp).
- A new warmer day pops its predecessors and records the day gap.
Edge cases to catch in interview
- Monotonic increasing temps → every ans[i] = 1 except the last (0).
- Monotonic decreasing temps → all zeros.
- All equal temps — strictly warmer is required, so all zeros.
Examples
Example 1
[1,1,4,2,1,1,0,0]{"temps":[73,74,75,71,69,72,76,73]}
Example 2
[1,1,1,0]{"temps":[30,40,50,60]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed