Workspace Daily Temperatures
0d
DSA Problem Sheet

Daily Temperatures

Return the distance to the next strictly warmer day for each position. Return zero if it never becomes warmer.

EXECUTION LAB

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 out

Visualizer

Step 1 of 8

Empty structure

Push this position until a larger value arrives

Push this position until a larger value arrives.

Variable watch

i 0top 0stack [0,0,0,0]out [0,0,0,0]

Step explanation

Push this position until a larger value arrives.

comparisons 2reads 0writes 1swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(n) space

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 1A new taller spectator becomes the first taller neighbour visible to a stack of shorter spectators.
Hint 2Store unresolved indices in a decreasing stack. A new larger value answers every smaller item on top.
Hint 3Step 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?