Stacks & queuesAnimated
Next Smaller Element
Same idea with the comparison reversed.
Time
O(n)
Extra space
O(n)
Use it for
Next smaller value to the right.
How it works
- For each item we want the first smaller item to its right.
- Scan left to right with a stack of items waiting for an answer.
- A new item smaller than the top is its answer: pop and record.
- Push the new item. Leftovers have no answer.
Watch it run
Loading animation…