Min Stack (LeetCode 155): Solution and Explanation
Design a stack that supports push, pop and top, plus a getMin operation that returns the smallest element currently in the stack. Every operation must run in constant time.
Watch it run step by step
Try your own input and write the code →Intuition
A plain stack already gives you push, pop and top in constant time. The challenge is getMin. The naive version scans the whole stack on every call, which is O(n). Keeping a single variable for the current minimum is the next idea, and it works for pushes, but it breaks on pops: if you pop the element that was the minimum, you have no idea what the previous minimum was without rescanning.
The key observation is that a stack only ever changes at the top. So the minimum of the stack is fully determined by its depth. When the stack has three elements, its minimum is the minimum of those three, and that does not change until the third element is popped. If you remember the minimum for every depth, a pop simply reverts to the minimum for the previous depth.
That is exactly what the second stack, minStack, stores. Every time you push a value, you also push the minimum of that value and the current top of minStack. Every time you pop, you pop both stacks together. The top of minStack is then always the minimum of everything currently in the main stack.
The cost is extra memory, one additional entry per element, but every operation becomes a constant number of list operations. It is a small, clean example of trading space for time by caching a running aggregate alongside the data.
Approach: Two stacks with running minimum
- Initialize two empty lists,
stackfor values andminStackfor the running minimum. - In
push(val), appendvaltostack, then appendmin(val, minStack[-1])tominStack, or justvalwhenminStackis empty. - In
pop(), pop from both stacks so their depths stay aligned. - In
top(), returnstack[-1]. - In
getMin(), returnminStack[-1], the minimum at the current depth.
Step-by-step example
push(-2), push(0), push(-3), getMin(), pop(), top(), getMin()
- push(-2):
stack= [-2] andminStack= [-2]. - push(0): the minimum of 0 and -2 is -2, so
stack= [-2, 0] andminStack= [-2, -2]. - push(-3): the minimum of -3 and -2 is -3, so
stack= [-2, 0, -3] andminStack= [-2, -2, -3]. getMin() returns -3. - pop(): both stacks lose their top, giving
stack= [-2, 0] andminStack= [-2, -2]. - top() returns 0 and getMin() returns -2, the correct minimum after -3 was removed.
Code: Python, Java, C++
1class MinStack:
2 def __init__(self):
3 self.stack = []
4 self.minStack = []
5
6 def push(self, val: int) -> None:
7 self.stack.append(val)
8 val = min(val, self.minStack[-1] if self.minStack else val)
9 self.minStack.append(val)
10
11 def pop(self) -> None:
12 self.stack.pop()
13 self.minStack.pop()
14
15 def top(self) -> int:
16 return self.stack[-1]
17
18 def getMin(self) -> int:
19 return self.minStack[-1]1class MinStack {
2 private Stack<Integer> stack;
3 private Stack<Integer> minStack;
4
5 public MinStack() {
6 stack = new Stack<>();
7 minStack = new Stack<>();
8 }
9
10 public void push(int val) {
11 stack.push(val);
12 val = Math.min(val, minStack.isEmpty() ? val : minStack.peek());
13 minStack.push(val);
14 }
15
16 public void pop() {
17 stack.pop();
18 minStack.pop();
19 }
20
21 public int top() {
22 return stack.peek();
23 }
24
25 public int getMin() {
26 return minStack.peek();
27 }
28}1class MinStack {
2 stack<int> s;
3 stack<int> minS;
4public:
5 MinStack() {
6
7 }
8
9 void push(int val) {
10 s.push(val);
11 val = min(val, minS.empty() ? val : minS.top());
12 minS.push(val);
13 }
14
15 void pop() {
16 s.pop();
17 minS.pop();
18 }
19
20 int top() {
21 return s.top();
22 }
23
24 int getMin() {
25 return minS.top();
26 }
27};Time and space complexity
O(1)
Each operation performs a constant number of list appends, pops or index reads, all amortized O(1).
O(n)
The min stack stores one entry for every element in the main stack, so memory is about twice that of a plain stack.
Other approaches
Min stack that only grows on new minimums (time O(1), space O(n))
Push onto minStack only when the new value is less than or equal to its top, and pop from it only when the popped value equals its top. It saves memory when the minimum rarely changes, but you must keep the <= comparison to handle duplicates.
Single stack with encoded differences (time O(1), space O(n))
Store the difference between each value and the current minimum, and update the minimum when a negative difference appears. It uses only one stack and one variable, but the arithmetic is error prone and can overflow in fixed-width integers.
Common mistakes
- Tracking the minimum in a single variable, which cannot recover the previous minimum after the current minimum is popped.
- Popping only from the main stack, which leaves
minStackout of sync and returns stale minimums. - In the space-saving variant, pushing to the min stack only on strictly smaller values. A duplicate minimum then gets lost when one copy is popped.
- Reading
minStack[-1]without checking whether it is empty during the very first push.
Frequently asked questions
How do you get the minimum of a stack in O(1) time?
Keep a second stack where each entry is the minimum of all values at or below that depth. The top of that stack is always the current minimum, and popping both stacks together keeps it correct.
Can Min Stack be implemented with only one stack?
Yes. You can push pairs of (value, current minimum) onto a single stack, which is the same idea in one structure. You can also encode differences from the minimum to avoid the extra field.
What is the space complexity of Min Stack?
It is O(n), since the auxiliary stack holds one minimum per element. The optimized variant can use less in practice but is still O(n) in the worst case.
Why does popping work correctly?
The minimum at each depth depends only on the elements at or below it. Removing the top element exposes the previous depth, whose minimum was already recorded.