Min Stack
Build a stack that also returns its smallest value in O(1), by storing the minimum next to every value.
The problem
Design a class MinStack with the usual stack calls push(val), pop() and top(), plus getMin(), which returns the smallest value currently in the stack. Every call must run in O(1) time. You can assume pop, top and getMin are only called when the stack is not empty.
Input MinStack(), push(4), push(1), push(6), getMin(), pop(), top(), pop(), getMin()
Output [null, null, null, null, 1, null, 1, null, 4]
After the 1 is popped, the minimum goes back to 4, the smallest value still in the stack.
Input MinStack(), push(2), push(2), push(7), pop(), pop(), getMin(), top()
Output [null, null, null, null, null, null, 2, 2]
The minimum 2 was pushed twice, so removing one copy still leaves 2 as the minimum.
Key constraint: getMin has to be O(1), so you can't scan the stack to find the smallest value.
How to spot the pattern
- A stack where you also need a summary (here the minimum) of everything inside it, instantly.
- Values only enter and leave at the top, so each entry's view of the values below it never changes.
The idea
A stack only changes at the top, so while a value sits in the stack, the values below it stay exactly the same. That means the minimum of the stack at the moment you push a value stays correct for as long as that value is there. So store that minimum next to the value: getMin reads it from the top entry, and pop automatically brings back the minimum saved in the entry below.
Brute force: Keep a plain stack and scan all of it on every getMin call, which costs O(n) per call.
Step by step
- 1Keep one stack of pairs: a value, and the smallest value from that entry down to the bottom.
- 2
push(val): the new minimum isvalif the stack is empty, otherwise the smaller ofvaland the top entry's minimum; push the pair. - 3
pop(): remove the top pair, which brings back the minimum stored in the pair below. - 4
top()returns the value of the top pair, andgetMin()returns its stored minimum.
See the pattern move
The stacks pattern on a small example. Step through it, or press play.
Code
class MinStack:
def __init__(self):
# Each entry is (value, smallest value from this entry down to the bottom).
self.stack = []
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 getMin(self) -> int:
return self.stack[-1][1]Complexity
Time
O(1)
Space
O(n)
Every call touches only the top of the stack; storing a minimum with each value doubles the memory, which is still O(n).
Watch out for
- Keeping a single
minvariable: after you pop the minimum, you have no way to know the previous one. - With a separate min stack, pushing only when a value is strictly smaller than the current minimum: popping one copy of a repeated minimum then removes it too early, so push when the value is smaller or equal.
- In Java, comparing two
Integerobjects from two stacks with==, which compares references and fails for values outside -128 to 127; useequalsor plainints.
Follow-up questions
Can you use less memory than one stored minimum per value?
Use a second stack that receives a value only when it is less than or equal to the current minimum, and pop from it when the popped value equals its top. When new minimums are rare this saves memory, but the worst case is still O(n).
Can you do it with a single extra number instead of extra storage per value?
Yes, with an encoding trick: when a new minimum arrives, push 2 * val - min (which is smaller than val) and update min; when you pop a value smaller than min, the old minimum was 2 * min - popped. It needs 64-bit math to avoid overflow and is hard to read, so the pair version is the safer interview answer.
In Hinglish
Har value ke saath us waqt ka minimum bhi stack mein rakh do. Pop karte hi purana minimum apne aap wapas aa jaata hai.