CodeArchon

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.

1def warmer_day_countdown(temps: list[int]) -> list[int]:
2 ans = [0] * len(temps)
3 st: list[int] = []
4 for i, t in enumerate(temps):
5 while st and temps[st[-1]] < t:
6 j = st.pop()
7 ans[j] = i - j
8 st.append(i)
9 return ans
Variables
i=0

How to think about it

  1. Brute force compares every (i, j) → O(n²).
  2. Insight: once day j finds a warmer day, we never need j again.
  3. Keep days without a warmer successor on a stack (decreasing by temp).
  4. 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