- Interview Questions
- /
- Problems
- /
- Min Stack
Min Stack
Build a stack that can also report its smallest element in constant time. A short design question about storing just enough extra state on each push. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
Design a class MinStack that behaves like a normal stack but can also tell you its current minimum at any moment.
Implement:
MinStack()creates an empty stack.push(val)putsvalon top of the stack.pop()removes the top element. It returns nothing.top()returns the top element without removing it.getMin()returns the smallest value currently in the stack.
Every operation must run in O(1) time. pop, top and getMin are only ever called when the stack is non-empty.
In the tests, each case is a list of operations and their arguments. The first operation constructs the stack, and the expected output lists what each call returns (null for the constructor, push and pop).
Example 1
- Input
- ["MinStack", "push", "push", "push", "getMin", "pop", "pop", "getMin", "top"] [[], [6], [2], [9], [], [], [], [], []]
- Output
- [null, null, null, null, 2, null, null, 6, 6]
With 6, 2, 9 on the stack the minimum is 2. Popping 9 and then 2 leaves only 6, which is now both the top and the minimum.
Example 2
- Input
- ["MinStack", "push", "push", "push", "pop", "getMin", "pop", "getMin"] [[], [4], [1], [1], [], [], [], []]
- Output
- [null, null, null, null, null, 1, null, 4]
The minimum 1 was pushed twice. Popping one copy still leaves a 1 in the stack, so getMin stays 1 until the second copy is gone.
Constraints
- -2³¹ ≤ val ≤ 2³¹ - 1
- pop, top and getMin are only called on a non-empty stack.
- At most 3 × 10⁴ calls in total.
Practice
Runs 11 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Min Stack in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Min Stack
Pattern: Stack with running minimum
A stack only ever changes at the top. That means the minimum of the stack is fully determined by which elements are below the top, and those never change while the top element is sitting there.
So when you push a value, you already know the answer getMin should give for as long as that value is on top: the smaller of the new value and the minimum just below it. Store that number alongside the value. Popping then automatically "restores" the old minimum, because it's sitting in the entry underneath. You never have to search for a new minimum after removing the old one.
Approach 1: Plain stack, scan on getMin
Keep an ordinary array and walk it to find the smallest value whenever getMin is called. push, pop and top are O(1), but getMin is O(n), which fails the requirement.
Time O(n) for getMin · Space O(n)
Approach 2: Second stack of minimums
Keep a main stack and a mins stack. On push, also push onto mins if the value is ≤ its top. On pop, pop mins too if the removed value equals its top. This uses less memory when minimums change rarely, but the ≤ versus < detail is easy to get wrong with duplicates.
Time O(1) · Space O(n)
Approach 3: Store (value, minimum so far) pairs
Each stack entry is a pair: the pushed value and the minimum of the stack including that value.
push(val): the new minimum isvalif the stack is empty, otherwisemin(val, top entry's minimum). Push the pair.pop(): pop the pair. The entry below already holds the correct minimum.top()andgetMin(): read the two halves of the top pair.
Time O(1) · Space O(n)
| Approach | Time | Space |
|---|---|---|
| Plain stack, scan on getMin | O(n) for getMin | O(n) |
| Second stack of minimums | O(1) | O(n) |
| Store (value, minimum so far) pairs | O(1) | O(n) |
Solution code
Try the practice editor first. Both solutions pass every test above.
Min Stack solution in Python
class MinStack:
def __init__(self):
self.stack = [] # (value, minimum including this value)
def push(self, val: int) -> None:
current_min = val if not self.stack else min(val, self.stack[-1][1])
self.stack.append((val, current_min))
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1][0]
def get_min(self) -> int:
return self.stack[-1][1]Min Stack solution in JavaScript
class MinStack {
constructor() {
this.stack = []; // [value, minimum including this value]
}
push(val) {
const n = this.stack.length;
const currentMin = n === 0 ? val : Math.min(val, this.stack[n - 1][1]);
this.stack.push([val, currentMin]);
}
pop() {
this.stack.pop();
}
top() {
return this.stack[this.stack.length - 1][0];
}
getMin() {
return this.stack[this.stack.length - 1][1];
}
}Common mistakes
- Keeping a single `min` variable. After the minimum is popped there is no way to know the next smallest value without scanning.
- In the two-stack version, only pushing to `mins` when the value is strictly smaller. Pushing a duplicate minimum and popping one copy then loses the minimum while another copy is still in the stack.
- Comparing against the top of the main stack instead of the stored minimum when computing the new running minimum.
- Forgetting that the stack can empty out and be reused, so the "stack is empty" branch in push has to run again later.
What interviewers look for
The key sentence is "the minimum below an element can't change while that element is on the stack, so I can cache it at push time." Say it before you code; it shows you understand why the trick is safe rather than having memorized it.
If you choose the two-stack version, call out the duplicate case explicitly and walk through push 1, push 1, pop, getMin. Interviewers often ask for exactly that trace.
Follow-up questions
Can you do it with O(1) extra space beyond the stack itself?
Yes, by storing encoded values. Keep one `min` variable; when pushing a value smaller than `min`, push `2 * val - min` instead and set `min = val`. On pop, if the popped entry is below `min`, it was encoded, so restore `min = 2 * min - entry`. It works but needs care with integer overflow, so mention using a wider type.
How would you also support getMax?
Store a third field, the running maximum, with each entry, computed the same way. Every operation stays O(1).
What about a queue that reports its minimum?
Build the queue from two min-stacks (an in-stack and an out-stack). The queue minimum is the smaller of the two stacks' minimums, and each element moves between stacks at most once, so operations are amortized O(1). A monotonic deque is the other common answer.
Companies that ask Min Stack
Min Stack is tagged by 120 companies in our interview dataset. The score shows how often it comes up at each company.
- Snapchat100%
- Paytm100%
- Zenefits100%
- Buffer96%
- Discord94%
- Grid Dynamics94%
- Tinkoff93.8%
- Odoo92.7%
- Informatica89.2%
- Zipline89%
- Outreach87%
- Diasorin84%
- The Home Depot83%
- Acquia81%
- Udacity81%
- Vanta81%
- R381%
- Ricoh Usa80%
- Sisense80%
- Sigmoid80%
- Snap79.6%
- Revature79%
- Hashicorp78%
- Nike76.3%
and 96 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required