Problem Statement

Daily Temperatures

You get a list of daily temperatures. For each day, you want to know how many days you have to wait until it gets warmer. If it never gets warmer after that day, the answer for that day is 0. So you build a new list the same length as the input, where each spot holds the number of days to wait.

easyStackStackTime: O(n) · Space: O(n)

Signals to notice

find next warmer daynext greater elementlook forward in array

Brute force first

For each day, scan forward to find the next warmer temperature. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Use a monotonic decreasing stack of indices; pop when current temp is warmer. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Trace it on temperatures=[73,74,75,71,69,72,76,73]

i=0 t=73: stack empty -> push. stack=[0], res=[0,0,0,0,0,0,0,0]
i=1 t=74: 74>73 pop0 res[0]=1; push1. stack=[1]
i=2 t=75: 75>74 pop1 res[1]=1; push2. stack=[2]
i=3 t=71: 71<75 push3. stack=[2,3] | i=4 t=69: 69<71 push4. stack=[2,3,4]
i=5 t=72: 72>69 pop4 res[4]=1; 72>71 pop3 res[3]=2; 72<75 stop; push5. stack=[2,5]
i=6 t=76: 76>72 pop5 res[5]=1; 76>75 pop2 res[2]=4; push6. stack=[6]
i=7 t=73: 73<76 push7. stack=[6,7]
End: return res=[1,1,4,2,1,1,0,0]

What must stay true

The stack holds indices of days still waiting for a warmer day, in decreasing temperature order. As long as that statement keeps holding, you can trust the steps built on top of it.

Shape of the loop

result = array of zeros, length n
stack = []                  // holds indices, temps decreasing
for i, temp in temperatures:
    while stack and temp > temperatures[stack.top]:
        idx = stack.pop(); result[idx] = i - idx
    stack.push(i)
return result

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Storing temperatures instead of indices — you need indices to calculate the day difference. The fix is usually to return to the meaning of each move, not just the steps themselves.

Stack Pattern