The next bigger value on the right
For every item, find the first value to its right that is bigger, by keeping a stack of items still waiting for something bigger. About 14 minutes.
Items waiting for an answer
For each number, you want the first bigger number to its right. Think of every number as waiting for that answer. When a new number arrives, it answers every waiting number that is smaller than it.
Keep the waiting numbers on a stack, as positions. The waiting numbers on the stack always go from biggest at the bottom to smallest on top, so the ones that a new value beats are exactly the ones on top.
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
res[stack.pop()] = x
stack.append(i)2 arrives. Nothing is waiting, so push it. Waiting: 2.
Items that never get answered
When the scan ends, the positions still on the stack never found a bigger value to their right. Their answer stays at minus one, so start the answer list filled with minus one and write to it only when an item is answered.
Each position goes onto the stack once and comes off at most once. That is why the whole pass costs about two steps per item, no matter how many items are popped by one value.
res = [-1] * len(nums) stack = []
A value arrives that equals the number on top of the stack. What happens?
- AThe value is pushed, since equal is not bigger
- BThe top is popped and answered
- CThe value is ignored
Show the answer
The value is pushed, since equal is not bigger. Only a strictly bigger value answers a waiting item.
Next greater element
Given an array nums, return an array answer of the same length where answer[i] is the first value to the right of position i that is strictly greater than nums[i], or -1 if there is none.
nums = [2, 1, 2, 4, 3] → [4, 2, 4, -1, -1]
1 ≤ length of nums ≤ 100,000 · -1,000,000,000 ≤ nums[i] ≤ 1,000,000,000