Next Greater Value
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.
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] = -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 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} ⇒ [7,4,7,-1]
Edge case 1 · {"values":[],"target":0} ⇒ []
Edge case 2 · {"values":[2,2],"target":0} ⇒ [-1,-1]
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?