Stack
Medium
Min Stack
Design a stack that supports retrieving the minimum element in constant time.
10 min read
Problem Understanding
Design a stack that supports push, pop, top, and getMin operations, all in O(1) time.
push(val): Pushes element val onto stack.pop(): Removes element on top of stack.top(): Gets the top element.getMin(): Retrieves minimum element in the stack.
Algorithm Strategy
A standard stack gives O(1) push/pop, but finding the minimum usually takes O(N). To get O(1) min, we trade Space for Time.
Strategy:
Maintain a second stack, minStack. whenever we push a value x onto the mainStack, we also push min(x, minStack.top()) onto the minStack. The top of minStack always represents the minimum of the mainStack at that height.
Interactive Visualization
Step 1 / 1
Empty Stack
Top Index: -1Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
