Continue learning
Practice related DSA questions in the same topic.
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.
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 outEmpty structure
Push this position until a larger value arrives.
Push this position until a larger value arrives.
A new taller spectator becomes the first taller neighbour visible to a stack of shorter spectators.
Store unresolved indices in a decreasing stack. A new larger value answers every smaller item on top.
O(n) time · O(n) auxiliary space
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]
Popping on equality treats an equal value as a strict improvement.
How many times can any index be pushed or popped?