Min stack
Store, next to every value, the smallest value at or below it in the stack. The minimum of the whole stack is then the one stored with the top, so push, pop, top and getMin are all O(1).
How to recognise it
- A stack must also report its minimum (or maximum) at any time.
- Every operation must be O(1).
- A running minimum must survive pops: you need what it was before.
The idea
Each entry is a pair (value, min so far). When you push x, the new minimum is min(x, top's min). Popping takes
the pair away, and the minimum stored in the pair below is the correct one again, because it was computed before x
arrived.
| Operation | Stack after (value, min) | getMin |
|---|---|---|
| push -2 | (-2, -2) | -2 |
| push 0 | (-2, -2) (0, -2) | -2 |
| push -3 | (-2, -2) (0, -2) (-3, -3) | -3 |
| pop | (-2, -2) (0, -2) | -2 |
A version with less memory
A second stack can hold only the minimums, pushed when x is at most the current minimum and popped when the popped
value equals it. It uses less memory when the minimum rarely changes, but the pair version is simpler to get right.
Common mistakes
- In the two-stack version, pushing to the minimum stack only when
xis strictly smaller, so duplicate minimums are lost. - Comparing boxed
Integervalues with==in Java.
Problems
- Min Stackmediumguide ready