Given daily temperatures, return an array where answer[i] is the number of days until a warmer temperature appears, or 0 if none ever does.
The key insight: you need the next greater element to the right, and a monotonic stack answers that in one pass. The stack stores indices whose warmer day is not yet found, with temperatures strictly decreasing from bottom to top. Scan right to left: while the top of the stack is a colder-or-equal day, pop it — it can never be the warmer day for this index or anything left of it. Whatever remains on top is the next warmer day; the distance is the index difference. If the stack empties, the answer is 0.
Approach in steps:
- Walk the array from right to left, maintaining a stack of candidate indices.
- Pop while
temps[stack[-1]] <= temps[i]. - Answer is
stack[-1] - iif the stack is non-empty, else 0; then pushi.
def dailyTemperatures(temps):
n = len(temps)
ans = [0] * n
stack = []
for i in range(n - 1, -1, -1):
while stack and temps[stack[-1]] <= temps[i]:
stack.pop()
ans[i] = stack[-1] - i if stack else 0
stack.append(i)
return ansTime is O(n) — each index enters and leaves the stack once; space O(n).
Trickiest edge case: equal temperatures. [30,40,40] — the second 40 gets answer 0, and the <= in the pop condition matters: an equal temperature is not warmer, so it must be popped. Missing that turns <= into < and returns the wrong distance.