Daily Temperatures
Return the distance to the next strictly warmer day for each position. Return zero if it never becomes warmer.
Return the distance to the next strictly warmer day for each position. Return zero if it never becomes warmer.
Input and constraints
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): out = [0] * (len(values)) stack = [0] * (len(values)) top = 0 i = 0 while (i < len(values)): out[i] = 0 while ((top > 0) and (values[stack[(top - 1)]] < values[i])): top = (top - 1) old = stack[top] out[old] = (i - old) stack[top] = i top = (top + 1) i = (i + 1) return outVisualizer
Step 1 of 8Empty structure
Push this position until a larger value arrives
Push this position until a larger value arrives.
Variable watch
Step explanation
Push this position until a larger value arrives.
Worked explanation
A new taller spectator becomes the first taller neighbour visible to a stack of shorter spectators.
Guided solution
Store unresolved indices in a decreasing stack. A new larger value answers every smaller item on top.
O(n) time · O(n) auxiliary space
Examples
Worked example · {"values":[5,3,4,7],"target":0} ⇒ [3,1,1,0]
Edge case 1 · {"values":[],"target":0} ⇒ []
Edge case 2 · {"values":[2,2],"target":0} ⇒ [0,0]
Progressive hints
Hint 1
A new taller spectator becomes the first taller neighbour visible to a stack of shorter spectators.Hint 2
Store unresolved indices in a decreasing stack. A new larger value answers every smaller item on top.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Popping on equality treats an equal value as a strict improvement.
Interview follow-up
How many times can any index be pushed or popped?