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