Stacks & queuesAnimated
Min Stack
Keep a second stack of running minimums.
Time
O(1)
Extra space
O(n)
Use it for
Getting the minimum in constant time.
How it works
- A normal stack cannot tell you its minimum without scanning.
- Keep a second stack alongside it: when pushing x, also push min(x, current minimum).
- Popping removes from both stacks, so the minimum is always the top of the helper stack.
- push, pop and getMin are all O(1).
Watch it run
Loading animation…