← Back to DSA Animator
Min Stack LC #155 Medium Auxiliary Stack
Problem

Design a stack that supports push, pop, top, and retrieving the minimum element — all in O(1) time.

Example 1
Input: push(-2), push(0), push(-3), getMin(), pop(), top(), getMin()
Output: [-3, 0, -2]
Explanation: getMin()=−3 after three pushes; after pop(), top()=0 and getMin()=−2.
Example 2
Input: push(5), push(3), push(7), getMin(), pop(), getMin(), push(1), getMin()
Output: [3, 3, 1]
Explanation: Min is 3 even with 7 on top; after popping 7, min stays 3; push 1 makes min 1.
Constraints: −2³¹ ≤ val ≤ 2³¹−1  |  At most 3×10⁴ calls  |  pop/top/getMin on non-empty stack
Try Examples
Approach
Parallel Min Stack: each push also records current minimum
minStack[i] = min(value, minStack[top]). GetMin is O(1): just peek minStack
Stack Visualization
Select an example to begin
Main Stack
Min Stack
State
Operation
Main Top
Min Top
Stack Size
0
Step Logic
Press ▶ Play or Next Step to begin the animation.
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Init two empty stacks: stack (values) and minSt (running minimums)
2
push(val): push val to stack; push min(val, minSt.peek()) to minSt
3
pop(): pop both stacks simultaneously — they stay in sync
4
top(): peek main stack — O(1)
5
getMin(): peek minSt — always the current minimum, O(1)
Time (all ops)
O(1)
Space
O(n)
Why It Works

The min-stack mirrors the main stack level-for-level. Each entry minSt[i] stores the minimum of the entire main stack at that depth. When an element is popped, its corresponding min entry is also discarded — so minSt.peek() always reflects the current minimum without any scanning.