Daily Temperatures
Picture
Days at 73 and 71 are both waiting for something warmer. When 74 arrives, both questions can be answered immediately. Keep only unresolved days, with cooler recent days on top.
Predict
Why can we permanently remove the day at 71 when 74 arrives?
Walk through the small example
We scan in chronological order. No earlier scanned day answered it, and today is warmer, so today is its first valid answer.
Mental model and complete Python solution
The stack stores indices, because the output is a distance between days. Its temperatures are nonincreasing from bottom to top. A new temperature resolves a suffix of cooler waiting days; stop at the first equal or warmer day. Days left at the end have no future warmer day and keep zero.
What the function promises: Return a list of waiting distances, with zero where no strictly warmer future day exists.
def warmer_days(temperatures):
answer = [0] * len(temperatures)
waiting = []
for today, temperature in enumerate(temperatures):
while waiting and temperatures[waiting[-1]] < temperature:
earlier = waiting.pop()
answer[earlier] = today - earlier
waiting.append(today)
return answer
assert warmer_days([73, 71, 74]) == [2, 1, 0]
assert warmer_days([73, 73]) == [0, 0]
assert warmer_days([]) == []
Work and storage: O(n) time and O(n) extra space. Every index is pushed once and popped at most once; nested syntax does not imply quadratic work.
When to recognize it: Several waiting days can get their answer from the same new day. Keep unresolved days in temperature order.
Check before applying it: Equal temperatures are not warmer. Sorting temperatures would lose the original waiting distances.
Change one rule
We want the first future day that is at least as warm. Which comparison changes?
See what changes
Pop while the waiting temperature is less than or equal to today’s temperature. The equality rule follows the question, not a memorized template.
Connect
stacks: The newest unresolved candidate is checked first.
Largest Rectangle in Histogram: A shorter bar closes several waiting rectangles.
Problem reference: Daily Temperatures (Medium). The walkthrough and Python solution above are original course material.