Full answer
Problem
Given daily temperatures, return a list where answer[i] is the number of days after day i until a strictly warmer temperature, or 0 if there is none.
Example: [73, 74, 75, 71, 69, 72, 76, 73] gives [1, 1, 4, 2, 1, 1, 0, 0].
Constraints: 1 <= len(temps) <= 10^5, values between 30 and 100.
Brute force
For each day, scan forward until a warmer day: O(n^2) in the worst case, for example a long run of decreasing temperatures followed by one hot day.
Optimal approach
Stack of indices with decreasing temperatures.
For each day i:
- While the stack is not empty and
temps[stack[-1]] < temps[i]: popjand setanswer[j] = i - j. - Push
i.
Indices left on the stack at the end keep 0.
Why it works
Day i is the first warmer day for exactly those waiting days that are colder than it, and those are on top of the stack because waiting days are stored with decreasing temperatures. If the top is not colder, nothing below it is colder either, so the loop can stop. Each day is popped at the moment its first warmer day appears, which is the definition of the answer.
Complexity
O(n) time: each index is pushed once and popped at most once. O(n) space for the stack in the worst case (decreasing temperatures).
Code
def daily_temperatures(temps):
"""For each day, how many days until a warmer one (0 if none). Monotonic stack, O(n)."""
answer = [0] * len(temps)
stack = [] # indices whose temperatures are decreasing
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
j = stack.pop()
answer[j] = i - j # day i is the first warmer day after j
stack.append(i)
return answer
def brute(temps):
n = len(temps)
out = []
for i in range(n):
out.append(next((j - i for j in range(i + 1, n) if temps[j] > temps[i]), 0))
return out
if __name__ == "__main__":
for f in (daily_temperatures, brute):
assert f([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0]
assert f([30, 40, 50, 60]) == [1, 1, 1, 0]
assert f([30, 60, 90]) == [1, 1, 0]
assert f([50, 50, 50]) == [0, 0, 0]
assert f([]) == []
print("all tests passed")Save as a37_daily_temperatures.py and run python3 a37_daily_temperatures.py. It prints all tests passed (Python 3.13.5).
Edge cases
Equal temperatures do not count as warmer (< in the pop condition, so [50, 50, 50] gives all zeros). Strictly increasing input gives all 1s except the last. Strictly decreasing input leaves every index on the stack. Empty input returns an empty list.
Pattern
Monotonic stack for "next greater element". Variants: next smaller element (flip the comparison), previous greater element (scan from the other side), stock span, and the circular version (scan the list twice).
def daily_temperatures(temps):
"""For each day, how many days until a warmer one (0 if none). Monotonic stack, O(n)."""
answer = [0] * len(temps)
stack = [] # indices whose temperatures are decreasing
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
j = stack.pop()
answer[j] = i - j # day i is the first warmer day after j
stack.append(i)
return answer
def brute(temps):
n = len(temps)
out = []
for i in range(n):
out.append(next((j - i for j in range(i + 1, n) if temps[j] > temps[i]), 0))
return out
if __name__ == "__main__":
for f in (daily_temperatures, brute):
assert f([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0]
assert f([30, 40, 50, 60]) == [1, 1, 1, 0]
assert f([30, 60, 90]) == [1, 1, 0]
assert f([50, 50, 50]) == [0, 0, 0]
assert f([]) == []
print("all tests passed")Decreasing stack of indices; an O(n^2) forward-scan reference passes the same tests.
Complexity
Time: O(n). Space: O(n). Amortised: every index is pushed once and popped at most once.
By level
Fresher: Explains the brute force and the waiting-days idea, then writes the stack solution with indices. Should explain why each index is popped at most once.
Mid: Gives the amortised O(n) proof and adapts it to next smaller or previous greater variants. Handles equal temperatures correctly.
Senior: Generalises monotonic stacks to histogram, sum of subarray minimums and circular variants, and discusses offline versus streaming use. Solves the circular next greater element variant.
Key points
- Stack holds indices still waiting for a warmer day
- Pop while the top is colder than today
- Distance is i - j at the moment of popping
- Each index is pushed and popped once: O(n)
- Strictly warmer means < in the pop condition
Common mistakes
- Storing temperatures instead of indices
- Using <= and treating equal days as warmer
- Claiming O(n^2) because of the nested while loop
- Forgetting that unresolved days stay 0
Follow-ups
- How would you solve next greater element on a circular list?
- How would you compute the stock span?
- How do you find the previous smaller element?
Tips
- Explain "waiting days" in plain words
- Give the amortised argument for the inner loop
- Test equal temperatures
Evaluation rubric
- Correct monotonic stack
- Correct amortised analysis
- Handles equal values and unresolved days
- Clear explanation