Skip to content
mlmentorship

Daily Temperatures

For each day, find how many days pass before a warmer temperature.

Published · 15 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Daily Temperatures

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A list temperatures of integer daily temperatures in chronological order. Output. Return an equally long list whose entry at day i is the distance to its first warmer later day. Rules. Warmer means strictly greater; an equal temperature does not qualify. Return zero when no later day qualifies, not the number of remaining days. Preserve the input. An empty list returns []. Example. [73, 74, 75, 71, 69, 72, 76, 73] returns [1, 1, 4, 2, 1, 1, 0, 0]. Day 2 waits four days for 76; day 6 has no warmer later day.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Unresolved temperatures are nonincreasing; a strictly warmer day pops waiting indices and writes their first qualifying distances.

Problem trace

A warmer arrival resolves only colder waiting indices; answers measure index distance

A warmer arrival resolves only colder waiting indices; answers measure index distanceKeep waiting indices in nonincreasing temperature order. A warmer day pops colder entries and records their index distance. Day two resolves day one, not day zero. Day three resolves the remaining colder days. Equal temperatures do not qualify. Unresolved entries get zero after the scan. A higher reading on the same day changes degrees, not waiting time.Keep waiting indices; resolve onlycolder temperaturesIndex 0: 70 degreesbeforeemptyafterD070No colder waiting day to resolveIndex 1: 68 degreesbeforeD070afterD070D168No colder waiting day to resolveIndex 2: 69 degreesbeforeD070D168afterD070D269Record D1: 1 dayIndex 3: 80 degreesbeforeD070D269afterD380Record D2: 1 day; D0: 3 daysWaiting temperatures never rise fromleft to right.After the scan, unresolved D3 keepszero.Temperature change is vertical;waiting follows daily indices70068169280360Three days to the warmer readingTen degrees warmer; still a three-daywait.
Read it this way: Keep waiting indices in nonincreasing temperature order. A warmer day pops colder entries and records their index distance. Day two resolves day one, not day zero. Day three resolves the remaining colder days. Equal temperatures do not qualify. Unresolved entries get zero after the scan. A higher reading on the same day changes degrees, not waiting time. If the warmer day were ninety degrees at the same index three, would the waiting time change?
Full interview answer 15 min read
Reading depth

For each day, report how long the wait is until a strictly warmer day occurs.

Problem

Input. A list temperatures of integer daily temperatures in chronological order.

Output. Return an equally long list whose entry at day i is the distance to its first warmer later day.

Rules. Warmer means strictly greater; an equal temperature does not qualify. Return zero when no later day qualifies, not the number of remaining days. Preserve the input. An empty list returns [].

Example. [73, 74, 75, 71, 69, 72, 76, 73] returns [1, 1, 4, 2, 1, 1, 0, 0]. Day 2 waits four days for 76; day 6 has no warmer later day.

Picture: Resolve Only the Colder Waiting Days

Problem trace

Separate longer array: resolve colder waiting indices at their first warmer day

Input and goalFor each day, find how many days pass before a warmer temperature.
Initialize unanswered daysInitialize eight zero answers and an empty stack of waiting indices.
emptytop waiting day
temperatures[73, 74, 75, 71, 69, 72, 76, 73]layoutoldest to newestcurrentbefore day 0answer[0,0,0,0,0,0,0,0]actioninitialize
top waiting day
(0, 0)
temperatures
[73, 74, 75, 71, 69, 72, 76, 73]
layout
oldest to newest

Recognize it
Look for the first later greater value or the waiting distance to it; those words suggest keeping unresolved indices until a new value is large enough to answer them.
Keep true
After each day is appended, waiting indices increase from bottom to top while their temperatures are non-increasing, and every popped index receives its first strictly warmer later day.
Reuse it
For next-greater or next-smaller problems, store unresolved indices in a monotonic stack; the first value that violates the monotonic order resolves every eligible item popped from the top.
Initialize eight zero answers and an empty stack of waiting indices. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does day 2 receive answer 4 rather than a temperature difference?
Reference drawing

Problem trace

A warmer arrival resolves only colder waiting indices; answers measure index distance

A warmer arrival resolves only colder waiting indices; answers measure index distanceKeep waiting indices in nonincreasing temperature order. A warmer day pops colder entries and records their index distance. Day two resolves day one, not day zero. Day three resolves the remaining colder days. Equal temperatures do not qualify. Unresolved entries get zero after the scan. A higher reading on the same day changes degrees, not waiting time.Keep waiting indices; resolve onlycolder temperaturesIndex 0: 70 degreesbeforeemptyafterD070No colder waiting day to resolveIndex 1: 68 degreesbeforeD070afterD070D168No colder waiting day to resolveIndex 2: 69 degreesbeforeD070D168afterD070D269Record D1: 1 dayIndex 3: 80 degreesbeforeD070D269afterD380Record D2: 1 day; D0: 3 daysWaiting temperatures never rise fromleft to right.After the scan, unresolved D3 keepszero.Temperature change is vertical;waiting follows daily indices70068169280360Three days to the warmer readingTen degrees warmer; still a three-daywait.
Execution trace
Input and goalFor each day, find how many days pass before a warmer temperature.
Initialize unanswered daysInitialize eight zero answers and an empty stack of waiting indices.
emptytop waiting day
temperatures[73, 74, 75, 71, 69, 72, 76, 73]layoutoldest to newestcurrentbefore day 0answer[0,0,0,0,0,0,0,0]actioninitialize
top waiting day
(0, 0)
temperatures
[73, 74, 75, 71, 69, 72, 76, 73]
layout
oldest to newest

Recognize it
Look for the first later greater value or the waiting distance to it; those words suggest keeping unresolved indices until a new value is large enough to answer them.
Keep true
After each day is appended, waiting indices increase from bottom to top while their temperatures are non-increasing, and every popped index receives its first strictly warmer later day.
Reuse it
For next-greater or next-smaller problems, store unresolved indices in a monotonic stack; the first value that violates the monotonic order resolves every eligible item popped from the top.
Initialize eight zero answers and an empty stack of waiting indices. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does day 2 receive answer 4 rather than a temperature difference?
Read it this way: Keep waiting indices in nonincreasing temperature order. A warmer day pops colder entries and records their index distance. Day two resolves day one, not day zero. Day three resolves the remaining colder days. Equal temperatures do not qualify. Unresolved entries get zero after the scan. A higher reading on the same day changes degrees, not waiting time. If the warmer day were ninety degrees at the same index three, would the waiting time change?

Indices increase from bottom to top; their temperatures are nonincreasing, so equal values can remain together. This order makes every resolvable colder day accessible through consecutive pops at the top.

New dayResolutionStill waiting afterward
3: 71NoneDays 2, 3
4: 69NoneDays 2, 3, 4
5: 72Day 4 waits 1; day 3 waits 2Days 2, 5
6: 76Day 5 waits 1; day 2 waits 4Day 6
7: 73NoneDays 6, 7; final sentinels stay zero

If an earlier warmer day existed, it would already have popped the waiting index. Thus a pop certifies the first qualifying day, not merely some warmer day. Store indices, not just temperatures: day-earlier_day supplies the distance, and equal values can have different waits.

Code

def daily_temperatures(temperatures: list[int]) -> list[int]:
   answer = [0] * len(temperatures)
   waiting: list[int] = []

   for day, temperature in enumerate(temperatures):
      while waiting and temperatures[waiting[-1]] < temperature:
         earlier_day = waiting.pop()
         answer[earlier_day] = day - earlier_day
      waiting.append(day)

   return answer

Time and space are under ordinary comparison costs. Each index is pushed once and popped at most once; some never pop. Total inner-loop work is linear.

Change 1: Equal Temperature Also Qualifies

New task. Find the first later day at least as warm.

Picture and change. Pop with <=; equal days now resolve, leaving strictly decreasing waiting temperatures.

Code.

def days_until_at_least(temperatures):
   answer = [0] * len(temperatures)
   waiting = []
   for day, temperature in enumerate(temperatures):
      while waiting and temperatures[waiting[-1]] <= temperature:
         earlier = waiting.pop()
         answer[earlier] = day - earlier
      waiting.append(day)
   return answer

Check. [70, 70, 71] gives [1, 1, 0], instead of the original [2, 1, 0].

Use when. Equality qualifies; this is a changed contract, not an optimization.

Change 2: Find the Next Strictly Smaller Value

New task. Return distances to the first later smaller value.

Picture and change. Reverse the inequality; waiting values become nondecreasing. Keep indices and the no-answer zero sentinel.

Code.

def days_until_smaller(values):
   answer = [0] * len(values)
   waiting = []
   for index, value in enumerate(values):
      while waiting and values[waiting[-1]] > value:
         earlier = waiting.pop()
         answer[earlier] = index - earlier
      waiting.append(index)
   return answer

Check. [3, 2, 2, 1] gives [1, 2, 1, 0]; equal 2 does not resolve the earlier 2.

Use when. The qualifying direction reverses while the first-answer proof still applies.

Failure: Losing Strictness or Position

Replacing < with <= incorrectly accepts equal temperatures under the original task. Storing only values loses the coordinates needed for wait distances.

Transfer Check

Why is index order alone insufficient?

Reasoned Answer

It cannot identify which waiting days the new value resolves. Temperature monotonicity makes eligible indices contiguous at the top.

Unresolved Does Not Mean Impossible

During an ongoing stream, a waiting day may still receive a warmer future day. The final zero sentinel means no such day occurred within the completed input, not that none could ever occur.

Equal values must remain separately represented for strictly warmer queries. In [70, 70, 71], the two 70-degree days resolve together but have waits 2 and 1. Deduplicating them would lose an output position.

Both adaptations keep the one-push/at-most-one-pop accounting and linear auxiliary/output storage. Changing a threshold or adding expiry rules needs another proof of which waiting entries a new item can safely resolve. The bracket stack also stores unfinished work, but its pop rule follows nesting rather than temperature order.