Learning Outcome
After this lesson, you should be able to design a stack that supports push, pop, top, and getMin in constant time.
Problem Statement
Design a stack that supports standard stack operations and can return the minimum element currently in the stack in O(1) time.
| Operation | Result | Minimum |
|---|---|---|
push(-2), push(0), push(-3) | Stack has three values | -3 |
pop() | Removes -3 | -2 |
Brute Force Approach
Use a normal stack and scan all current values whenever getMin is called.
That makes getMin O(n), which breaks the requirement.
Optimized Approach
Store each pushed value together with the minimum value at that moment. Then the stack top always knows the current minimum.
Another valid version uses two stacks: one for values and one for minimums. The pair approach is compact and easy to dry-run.
Exact Pseudocode
stack = empty stack of (value, currentMin)
push(value):
if stack is empty:
currentMin = value
else:
currentMin = min(value, stack.top.currentMin)
push (value, currentMin)
pop():
pop stack
top():
return stack.top.value
getMin():
return stack.top.currentMin
Reference Code
class MinStack:
def __init__(self):
self.stack = []
def push(self, val):
current_min = val if not self.stack else min(val, self.stack[-1][1])
self.stack.append((val, current_min))
def pop(self):
self.stack.pop()
def top(self):
return self.stack[-1][0]
def getMin(self):
return self.stack[-1][1]Sample Dry Run
| Operation | Stored pair | Stack state | getMin |
|---|---|---|---|
push(-2) | (-2, -2) | [(-2,-2)] | -2 |
push(0) | (0, -2) | [(-2,-2),(0,-2)] | -2 |
push(-3) | (-3, -3) | [...,(-3,-3)] | -3 |
pop() | Remove top | [(-2,-2),(0,-2)] | -2 |
Complexity
| Operation | Time | Space |
|---|---|---|
push, pop, top, getMin | O(1) | O(n) total stack storage |
Edge Cases
- Duplicate minimum values.
- Negative values.
- Calling operations only when the stack is valid according to platform constraints.
Interview Checklist
- Do not scan the full stack in
getMin. - Store the minimum at each push.
- Handle duplicate minimums correctly.
FAQs
Why store the current minimum with every value?
Because after a pop, the previous stack top immediately tells the previous minimum.
Can two stacks be used instead?
Yes. One stack can store values and another can store minimums. The pair approach is equivalent.
What is the core pattern?
Auxiliary minimum state.