Min Stack
Design a stack supporting push, pop, top, and retrieving the minimum element in O(1) constant time by tracking the running minimum with every entry.
01The problem
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack()initializes the stack object.void push(int val)pushes the elementvalonto the stack.void pop()removes the element on the top of the stack.int top()gets the top element of the stack.int getMin()retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each operation.
| Operations | Output | Why |
|---|---|---|
push(-2), push(0), push(-3) | [null, null, null] | Stack items stored |
getMin() | -3 | Smallest value currently in stack is -3 |
pop() | null | Removes -3 |
top() | 0 | Top of stack is now 0 |
getMin() | -2 | Minimum element after popping -3 is restored to -2 |
Constraints: -2^31 <= val <= 2^31 - 1. Methods pop, top, and getMin are called on non-empty stacks. At most 3 * 10^4 calls.
02How to spot it
- A normal stack allows
O(1)push, pop, and top. - We need
getMin()inO(1)without scanning the stack (which would takeO(n)). - Notice what happens on pop: when the current minimum is popped, the minimum restores to whatever the minimum was before that element was added.
- Each state of the stack has a well-defined minimum. If each entry carries the minimum at that point in time, popping automatically rolls back to the previous minimum.
So: store value and current minimum together.
03Pseudocode
push(v):
m = v if empty else min(v, top.min)
push (v, m)
pop(): pop the pair
top(): top.value
getMin(): top.min- Each entry remembers the value and the minimum seen up to that level.
- Popping an entry naturally exposes the older minimum right at the new top.
- No searching is ever needed.
04Watch it work
stack [value (min so far)]
current min
none
operation
init
Initialize Min Stack. Each plate on the stack carries the value along with the minimum so far.
Pseudocode
- push(v):
- m = v if empty else min(v, top.min)
- push (v, m)
- pop(): pop the pair
- top(): top.value
- getMin(): top.min
Variables
- stackSize
- 0
05Step-by-step dry run
- 1
stack [value (min so far)]
current min
none
operation
init
Initialize Min Stack. Each plate on the stack carries the value along with the minimum so far.
stackSize = 0
- 2
stack [value (min so far)]
-2 (min:-2)0topcurrent min
-2
operation
push(-2)
Push -2. Minimum so far becomes min(-2, previousMin) = -2.
val = -2min = -2
- 3
stack [value (min so far)]
-2 (min:-2)00 (min:-2)1topcurrent min
-2
operation
push(0)
Push 0. Minimum so far becomes min(0, previousMin) = -2.
val = 0min = -2
- 4
stack [value (min so far)]
-2 (min:-2)00 (min:-2)1-3 (min:-3)2topcurrent min
-3
operation
push(-3)
Push -3. Minimum so far becomes min(-3, previousMin) = -3.
val = -3min = -3
- 5
stack [value (min so far)]
-2 (min:-2)00 (min:-2)1-3 (min:-3)2topcurrent min
-3
operation
getMin -> -3
Current minimum is -3 in O(1) time without searching.
min = -3
- 6
stack [value (min so far)]
-2 (min:-2)00 (min:-2)1topcurrent min
-2
operation
pop()
Popped top element -3. The previous minimum is restored instantly in O(1).
poppedVal = -3
- 7
stack [value (min so far)]
-2 (min:-2)00 (min:-2)1topcurrent min
-2
operation
top -> 0
Top element is 0.
top = 0
- 8
stack [value (min so far)]
-2 (min:-2)00 (min:-2)1topcurrent min
-2
operation
getMin -> -2
Current minimum is -2 in O(1) time without searching.
min = -2
06Java solution
import java.util.ArrayDeque;
import java.util.Deque;
public class MinStack {
private final Deque<int[]> stack = new ArrayDeque<>();
public void push(int val) {
int min = stack.isEmpty() ? val : Math.min(val, stack.peek()[1]);
stack.push(new int[]{val, min});
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek()[0];
}
public int getMin() {
return stack.peek()[1];
}
public static void main(String[] args) {
MinStack ms = new MinStack();
ms.push(-2);
ms.push(0);
ms.push(-3);
System.out.println(ms.getMin());
ms.pop();
System.out.println(ms.top());
System.out.println(ms.getMin());
}
}-3 0 -2
07Why it works
Because stack operations occur strictly at the top, adding or removing an element cannot alter the minimum of the elements sitting beneath it.
By pairing each value with the running minimum Math.min(val, currentMin) at insertion time:
- When a new item is pushed,
getMin()is simply the second value of the new pair. - When an item is popped, the history underneath remains untouched and the previous minimum is immediately available at
stack.peek()[1].
08Time and space
- Time complexity:
O(1)for all four methods:push,pop,top, andgetMin. - Space complexity:
O(n). We store an extra integer representing the minimum for each element pushed.
09Edge cases
- Duplicate minimum values: Pushing
-2, then another-2. Both pairs holdmin = -2. Popping one leaves the other intact. - Negative numbers: Handled seamlessly because comparisons work for all 32-bit signed integers.
- Single element: Both
top()andgetMin()equal that element's value.
10Common mistakes
- Tracking only a single
mininteger variable. If you only storeint min, popping the minimum leaves you with no way to know the second smallest element without scanning the entire stack inO(n). - Using an auxiliary min stack and missing duplicate minimums. If you maintain a separate stack for minimums and only push when
val < currentMin(using strict<instead of<=), popping a duplicate minimum removes the record prematurely.
11Other approaches
| Approach | getMin time | Space overhead | Trade-off |
|---|---|---|---|
| Linear scan on getMin | O(n) | O(1) extra | Fails problem requirement |
| Two separate stacks | O(1) | O(k) extra (k <= n) | Saves space on duplicate pushes, slightly more code |
Pair array [val, min] | O(1) | O(n) extra | Cleanest, simplest, impossible to bug |
12In the interview
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. Why is tracking only a single int min variable insufficient for MinStack?
2. What is stored in the pair pushed onto the stack for each value?
14Solve it yourself
Try implementing MinStack using the difference encoding trick (storing val - min in a single primitive long) without allocating int[] objects:
- When
val < min, the difference is negative. - How do you decode the previous
minwhen popping?