← HOME

Daily Temperatures.

— monotonic stack: each day waits in line for a warmer one. Push once, pop once per index → O(n).
Input[73, 74, 75, 71, 69, 72, 76, 73] PatternMonotonic Stack ComplexityO(n)
Step 0 of 0
Temperatures
Result (days until warmer)
Stack (indices)
empty
Action
Press NEXT to begin
Walk left to right. Each index waits in the stack for a warmer day. When a warmer day arrives, every smaller-temperature day below it gets its answer in one shot.

The trick — indices, not values.

The stack stores indices of days waiting for an answer, not the temperatures themselves. We need indices because the answer is *j − i* (how many days to wait), and we need both endpoints to compute that gap.

Stack invariant: indices on the stack are kept in strictly decreasing temperature order from bottom to top. As soon as a new day's temperature is greater than the top, that top index has found its warmer day → pop it, fill in its result.

Why O(n): each index is pushed exactly once and popped at most once. The inner while looks like nested loops, but its total work across the whole array is bounded by n. Result: 2n operations max → O(n).

Anything left on the stack at the end never found a warmer day → its slot in result stays at the default 0.

Same family pattern in: Next Greater Element, Largest Rectangle in Histogram, Trapping Rain Water, Sum of Subarray Minimums.