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.