Min Stack solution explained
The Min Stack solution stores, next to every value, the smallest value in the stack at the moment it was pushed. The current minimum is then always sitting at the top, so push, pop, top and get-minimum all run in O(1) time, at the cost of extra memory that is at most one more entry per item.
By Evin JohnPublished 7 min read
What you are asked to build
Design a stack class with four operations: push a value, pop the top value, read the top value without removing it, and report the smallest value currently in the stack. All four must take constant time. You can usually assume pop, top and get-minimum are never called on an empty stack, but ask, because the answer decides whether you need guard clauses.
| Operation | Stack after (bottom to top) | top | minimum |
|---|---|---|---|
| push 5 | 5 | 5 | 5 |
| push 3 | 5, 3 | 3 | 3 |
| push 7 | 5, 3, 7 | 7 | 3 |
| push 3 | 5, 3, 7, 3 | 3 | 3 |
| pop | 5, 3, 7 | 7 | 3 |
| pop | 5, 3 | 3 | 3 |
| pop | 5 | 5 | 5 |
The duplicate 3 is there on purpose. After the top 3 is popped, the other 3 is still in the stack, so the minimum must stay 3. Many first attempts get this wrong.
What the interviewer is checking
Min Stack is a small design question rather than an algorithm puzzle. The interviewer wants to see you notice that a minimum cannot be recomputed cheaply after a removal, and that the fix is to remember the answer at each level in advance. It also tests careful handling of ties and whether you can state the memory cost honestly. It is common in early rounds and as a warm-up before larger design problems such as an LRU cache.
The obvious version and its cost
Keep a plain list. Push and pop work on the end. When someone asks for the minimum, scan the whole list. That works, but get-minimum is O(n), and a caller who checks the minimum after every push turns n operations into O(n²) total work. Caching a single minimum variable does not rescue it either: once you pop the current minimum, you have no idea what the next smallest value is without scanning again.
class ScanningMinStack:
def __init__(self):
self._items = []
def push(self, value):
self._items.append(value)
def pop(self):
self._items.pop()
def top(self):
return self._items[-1]
def get_min(self):
return min(self._items) # O(n) every callConstant time: remember the minimum at every level
A stack only ever changes at the top. So the minimum of everything at or below a given item never changes while that item is in the stack. Compute it once, at push time, as the smaller of the new value and the minimum stored with the item underneath. Store the two together. Popping removes both, and the item now on top already carries the right minimum for what remains.
class MinStack:
def __init__(self):
self._items = [] # (value, smallest value at or below this item)
def push(self, value):
low = value if not self._items else min(value, self._items[-1][1])
self._items.append((value, low))
def pop(self):
self._items.pop()
def top(self):
return self._items[-1][0]
def get_min(self):
return self._items[-1][1]A common variant saves memory when the minimum rarely changes. Keep a second stack that only receives a value when it is less than or equal to the current minimum. On pop, if the departing value equals the top of that second stack, pop it there too. The JavaScript below uses this form. The less than or equal part is what handles duplicates: in the trace above, both 3s go onto the second stack, so popping one still leaves a 3 behind.
class MinStack {
constructor() {
this.values = [];
this.lows = []; // only values that were a new minimum (or tied it)
}
push(value) {
this.values.push(value);
if (this.lows.length === 0 || value <= this.lows[this.lows.length - 1]) {
this.lows.push(value);
}
}
pop() {
const value = this.values.pop();
if (value === this.lows[this.lows.length - 1]) this.lows.pop();
}
top() {
return this.values[this.values.length - 1];
}
getMin() {
return this.lows[this.lows.length - 1];
}
}Cost of each design
| Design | push / pop / top | get minimum | Extra memory |
|---|---|---|---|
| Plain stack, scan on request | O(1) | O(n) | None |
| Pairs of (value, minimum so far) | O(1) | O(1) | One extra number per item |
| Second stack of minimums | O(1) | O(1) | One extra number per new or tied low, n in the worst case |
The second-stack version only helps when values arrive in mostly rising order. Feed it a falling sequence and it stores every value twice, the same as the pair version. Say that rather than calling it strictly better.
Edge cases
- Repeated minimum values, as in the trace. With strict less than, the second stack loses track after one pop.
- Negative numbers and zero: nothing special, but some people initialize the minimum to 0 and get it wrong.
- Calls on an empty stack, if the interviewer does not rule them out. Decide whether to raise an error or return a sentinel, and say which.
- A long run of pushes followed by a long run of pops, which checks that the minimum climbs back correctly.
Mistakes to avoid
- Keeping one minimum variable and hoping pops will not touch it.
- Using a heap or sorted list for the minimum. It works but is O(log n), which misses the constant-time requirement.
- Pushing onto the minimum stack only on strictly smaller values, then losing a duplicate minimum on pop.
- Comparing object references instead of values in languages where boxed numbers are objects.
Follow-ups
- Constant extra memory beyond the stack itself. Push the difference between the value and the current minimum and keep one minimum variable; a negative stored difference marks a spot where the minimum changed. It works, but it is harder to read and can overflow in fixed-width integers.
- A max stack that can also remove the maximum. Removing from the middle breaks the simple trick; a balanced tree or a heap with lazy deletion is the usual answer.
- A queue that reports its minimum. Build the queue from two min stacks, or use a deque that keeps candidates in increasing order.
- Thread safety. Wrap each operation in a lock so the value and its stored minimum change together.
Saying it clearly
Fictional example
- Candidate
- A stack only changes at the top, so the minimum of everything below an item can't change while that item is there. I can compute it once when I push.
- Candidate
- I'll store pairs: the value and the minimum so far. Get-minimum reads the top pair, and pop just removes it, so everything is constant time.
- Candidate
- It costs one extra number per item. If memory matters, I can keep a separate stack of minimums that only grows on a new or tied low, and the tie case is why I use less than or equal.
Related walkthroughs
Evaluate Reverse Polish Notation uses a stack as a calculator, and Valid Parentheses uses one to match pairs. For a stack that stays sorted as it goes, see Daily Temperatures. Permutation in String covers the counting-window side of this set, and the coding problems hub lists them all.
Where Natively fits
If you practice design warm-ups like this one on a Mac or Windows machine, Natively can capture the prompt with a screenshot, suggest the value-plus-minimum idea, and raise the duplicate case for you to test. It also records a text transcript of your mock, so you can check afterward whether you stated the memory cost or skipped it. The coding interview assistant page has more detail.
Questions people ask
How do you get the minimum of a stack in O(1)?
Store the minimum so far alongside every pushed value, either as pairs or in a second stack of minimums. The top entry always holds the minimum of everything in the stack, so reading it is constant time.
Why does the second stack push on less than or equal?
Because the same minimum value can appear twice. If only strictly smaller values are recorded, popping one copy removes the recorded minimum while another copy is still in the stack.
What is the space complexity of Min Stack?
O(n) extra in the worst case. The pair version always stores one extra number per item; the second-stack version stores fewer when values mostly rise, but just as many when they fall.
Can Min Stack be done with O(1) extra space?
Yes, by pushing the difference between each value and the current minimum and keeping a single minimum variable. It works but is harder to explain and can overflow with fixed-size integers.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
