Full answer
Problem
Implement Stack with push(x), pop(), peek(), is_empty() and len(). Then implement MinStack with the same operations plus get_min(), all O(1).
Example: push 5, 3, 7, 3, 1: get_min() is 1. Pop once: get_min() is 3. Pop until only 5 is left: get_min() is 5.
Constraints: up to 10^5 operations; values can repeat. Operations on an empty stack raise IndexError.
Brute force
For get_min, scan the whole stack: O(n) per call. Rebuilding the minimum after every pop is also O(n).
Optimal approach
Stack:
- Back it with a list;
appendandpop()work at the end in O(1) amortised. - Raise
IndexErrorforpoporpeekon an empty stack. Returning a string such as"Stack is empty"mixes error signals with real values: a stack of strings could legitimately contain that text.
MinStack:
- Push
(value, min(value, current_min)). get_minreturns the second field of the top pair.popremoves the pair, which automatically restores the previous minimum.
Why it works
Every stack state is a prefix of the push history. The minimum of a prefix never depends on later elements, so storing it alongside each element records the minimum of every possible state. Popping returns to an earlier prefix whose minimum is already stored.
A memory-saving variant keeps a second stack holding only new minimums (push when x <= current_min, pop when the popped value equals it). The <= handles repeated minimum values.
Complexity
All operations O(1) time (amortised for list growth). Space O(n); the pair version stores two values per element.
Code
class Stack:
"""LIFO stack backed by a Python list. push/pop/peek are O(1) amortised."""
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack") # raise, do not return a string
return self._items.pop()
def peek(self):
if not self._items:
raise IndexError("peek from empty stack")
return self._items[-1]
def is_empty(self):
return not self._items
def __len__(self):
return len(self._items)
class MinStack(Stack):
"""Stack that also returns its minimum in O(1) by storing (value, min_so_far)."""
def push(self, item):
current_min = item if self.is_empty() else min(item, self._items[-1][1])
self._items.append((item, current_min))
def pop(self):
return super().pop()[0]
def peek(self):
return super().peek()[0]
def get_min(self):
if self.is_empty():
raise IndexError("min of empty stack")
return self._items[-1][1]
if __name__ == "__main__":
s = Stack()
assert s.is_empty() and len(s) == 0
s.push("maths")
s.push("physics")
assert s.peek() == "physics" and len(s) == 2
assert s.pop() == "physics" and s.pop() == "maths"
for op in (s.pop, s.peek):
try:
op()
raise AssertionError("expected IndexError")
except IndexError:
pass
m = MinStack()
for x in (5, 3, 7, 3, 1):
m.push(x)
assert m.get_min() == 1
m.pop()
assert m.get_min() == 3
m.pop()
m.pop()
assert m.get_min() == 3 and m.peek() == 3
m.pop()
assert m.get_min() == 5
print("all tests passed")Save as a34_stack.py and run python3 a34_stack.py. It prints all tests passed (Python 3.13.5).
Edge cases
Pop, peek or get_min on an empty stack raise IndexError. Repeated minimum values (5, 3, 7, 3 then pop one 3: minimum is still 3). Mixed types should be avoided in MinStack because min compares them.
Pattern
Stack (LIFO) and augmenting a data structure with extra per-element information. Stacks power undo history, function calls, bracket matching, expression evaluation and the monotonic stack problems.
class Stack:
"""LIFO stack backed by a Python list. push/pop/peek are O(1) amortised."""
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack") # raise, do not return a string
return self._items.pop()
def peek(self):
if not self._items:
raise IndexError("peek from empty stack")
return self._items[-1]
def is_empty(self):
return not self._items
def __len__(self):
return len(self._items)
class MinStack(Stack):
"""Stack that also returns its minimum in O(1) by storing (value, min_so_far)."""
def push(self, item):
current_min = item if self.is_empty() else min(item, self._items[-1][1])
self._items.append((item, current_min))
def pop(self):
return super().pop()[0]
def peek(self):
return super().peek()[0]
def get_min(self):
if self.is_empty():
raise IndexError("min of empty stack")
return self._items[-1][1]
if __name__ == "__main__":
s = Stack()
assert s.is_empty() and len(s) == 0
s.push("maths")
s.push("physics")
assert s.peek() == "physics" and len(s) == 2
assert s.pop() == "physics" and s.pop() == "maths"
for op in (s.pop, s.peek):
try:
op()
raise AssertionError("expected IndexError")
except IndexError:
pass
m = MinStack()
for x in (5, 3, 7, 3, 1):
m.push(x)
assert m.get_min() == 1
m.pop()
assert m.get_min() == 3
m.pop()
m.pop()
assert m.get_min() == 3 and m.peek() == 3
m.pop()
assert m.get_min() == 5
print("all tests passed")List-backed Stack that raises IndexError on empty access; MinStack stores (value, min so far) pairs.
Complexity
Time: O(1) per operation (amortised for push). Space: O(n). The two-stack variant uses less memory when the minimum rarely changes.
By level
Fresher: Implements the list-backed stack with IndexError on empty access and gives everyday uses such as undo. Should state the cost of each operation.
Mid: Builds the min stack with pairs or a second stack, handles duplicate minimums and explains the prefix argument. Handles repeated minimum values.
Senior: Discusses memory trade-offs between variants, thread safety, and extends the idea to min queues built from two min stacks. Can explain the memory cost of the pair version against the two-stack version.
Key points
- Stack is last in, first out
- Use the end of a Python list for O(1) push and pop
- Raise IndexError on empty pop or peek
- Min stack stores the minimum at each level
- Popping restores the previous minimum for free
Common mistakes
- Returning an error string instead of raising
- Pushing and popping at the front of a list (O(n))
- Recomputing the minimum after each pop
- Using < instead of <= in the two-stack min variant
Follow-ups
- How would you add get_max?
- Can you implement a stack with queues?
- How would you build a min queue?
Tips
- Name LIFO and a real example such as undo
- Explain why raising is better than a sentinel string
- Trace the min stack with a repeated minimum
Evaluation rubric
- Correct LIFO operations
- Correct empty handling
- O(1) get_min with correct justification
- Clear code