Given an array of integers temperatures, we need to return an array answer such that answer[i] is the number of days you have to wait after the i-th day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] = 0.
Brute force nested loops take O(N^2) time. How does storing array indices instead of temperature values in a decreasing monotonic stack solve this in a single pass?
Here is the C++20 Monotonic Stack solution for Daily Temperatures. It stores day indices to compute elapsed days in
O(1).Complexity:
O(N)time andO(N)space with zero reallocations.This problem is the cleanest introductory template for the Monotonic Decreasing Stack pattern. Let’s look at why storing indices unlocks the distance calculation.
1. The Mental Model
Imagine people waiting in line holding temperature tickets. If temperatures are dropping:
[73, 71, 69], nobody has found a warmer day yet! So everyone has to stay waiting in line.Now, a warm day arrives:
72!69sees72 > 69. Their wait is over! They step out of line.71sees72 > 71. Their wait is over! They step out of line.73sees72 < 73.72is not warm enough for them! The person with73stays waiting in line, and the day with72joins the line behind them.2. Why Store Indices Instead of Values?
If you only push temperature numbers (e.g.
69) onto the stack, when a warmer day72pops69, you know that a warmer day happened, but you don’t know how many days elapsed!By pushing the array index
prev_dayonto the stack:You calculate the exact time difference in $O(1)$ and write directly to the output array!
Clean Python 3.12 Implementation
Complexity Breakdown
O(N). Every index is pushed onto the stack once and popped at most once. Total operations: $le 2N$.O(N)for the stack in the worst-case of strictly decreasing temperatures (e.g.[100, 90, 80, 70]).