Stacks & queuesAnimated
Previous Greater Element
Scan left to right, keeping a stack of candidates.
Time
O(n)
Extra space
O(n)
Use it for
Nearest larger value to the left.
How it works
- For each item we want the nearest larger item to its LEFT.
- Scan left to right keeping a stack of candidates in decreasing order.
- Pop candidates that are not larger than the current item.
- The item left on top is the answer; then push the current item.
Watch it run
Loading animation…