mediumStackAmazonBloomberg
Minimum-Aware Stack
Design a stack that supports push, pop, top, and getMin — each in O(1).
Implement a stack with: `push(x)`, `pop()`, `top()`, `getMin()`, every call O(1).
Choose approach
top
1/8
Narrationstep 1 of 8
Paired stacks: data holds pushed values, mins holds a running minimum. Push copies the new min; pop discards both tops.
Variables
ops=7
How to think about it
- A regular stack can't produce the min in O(1) without extra state.
- Store the running minimum per level in a parallel stack.
- Pushing x pushes min(x, old-top-min).
- Pop both stacks together.
- Top and getMin are just reads of each stack's top.
Edge cases to catch in interview
- pop/top/min on empty stack — treat as undefined behaviour (problem guarantees valid calls).
- Duplicates — mins stack stores them separately (correct).
Examples
Example 1
-3, (pop), 0, -2{"ops":[["push",-2],["push",0],["push",-3],["min"],["pop"],["top"],["min"]]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed