Min Stack
LeetCode 155 · Medium · solution, intuition & step-by-step walkthrough
Push (value, min so far) pairs.
This is how I solved Min Stack (LeetCode 155), a medium problem from the Stack / Queue Design pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Store, with every pushed value, the minimum of the stack at that moment. The current minimum is then always on top, and popping automatically restores the previous minimum.
Approach
- 1
push: pair the value with min(value, previous min).
- 2
pop: pop the pair.
- 3
top: first element of the top pair.
- 4
getMin: second element of the top pair.
How I solved it
Value + running-min pairsPythonO(1) per op
class MinStack:
def __init__(self):
self.items = []
def push(self, val: int) -> None:
if not self.items:
self.items.append((val,val))
else:
min_val = self.items[-1][1]
self.items.append((val,min(min_val,val)))
def pop(self) -> None:
self.items.pop()
def top(self) -> int:
if self.items:
item = self.items[-1]
return item[0]
return None
def getMin(self) -> int:
return self.items[-1][1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()Min Stack — FAQ
What is the intuition behind Min Stack?
Store, with every pushed value, the minimum of the stack at that moment. The current minimum is then always on top, and popping automatically restores the previous minimum.
How do you solve Min Stack (LeetCode 155)?
1. push: pair the value with min(value, previous min). 2. pop: pop the pair. 3. top: first element of the top pair. 4. getMin: second element of the top pair.
What is the time and space complexity of Min Stack?
Time: O(1) per operation. Space: O(n). (Accepted approach: Value + running-min pairs.)
What are common mistakes in Min Stack?
A single 'current min' variable can't recover the old min after a pop.