Continue learning
Practice related DSA questions in the same topic.
For each position, find the first strictly larger value to its right. Use -1 where no such position exists.
For each position, find the first strictly larger value to its right. Use -1 where no such position exists.
def solve(values, target): out = [0] * (len(values)) stack = [0] * (len(values)) top = 0 i = 0 while (i < len(values)): out[i] = -1 while ((top > 0) and (values[stack[(top - 1)]] < values[i])): top = (top - 1) old = stack[top] out[old] = values[i] 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} ⇒ [7,4,7,-1]
Edge case 1 · {"values":[],"target":0} ⇒ []
Edge case 2 · {"values":[2,2],"target":0} ⇒ [-1,-1]
Popping on equality treats an equal value as a strict improvement.
How many times can any index be pushed or popped?