The Runtime Theory
mediumleetcode#stack#monotonic-stack

Daily Temperatures

Find days until a warmer temperature using a monotonic decreasing stack.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in[73,74,75,71,69,72,76,73]

out[1,1,4,2,1,1,0,0]

in[30,40,50,60]

out[1,1,1,0]

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:

  1. Walk the array from right to left, maintaining a stack of candidate indices.
  2. Pop while temps[stack[-1]] <= temps[i].
  3. Answer is stack[-1] - i if the stack is non-empty, else 0; then push i.
python
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 ans

Time 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.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.