Stacks & queuesAnimated
Next Greater Element
A stack of waiting items resolves each when a bigger one arrives.
Time
O(n)
Extra space
O(n)
Use it for
For each item, the next larger one to its right.
How it works
- For each item we want the first larger item to its right.
- Scan left to right with a stack of items still waiting for their answer.
- When a new item is larger than the item on top of the stack, it is that item’s answer: pop and record.
- Then push the new item. Items left at the end have no answer.
Watch it run
Loading animation…