Consider a Min Stack that supports push, pop, and getMin operations. What is the output of the getMin calls after the following operations?
push(5)
push(3)
push(7)
pop()
getMin()
pop()
getMin()
class MinStack: def __init__(self): self.stack = [] self.min_stack = [] def push(self, val): self.stack.append(val) if not self.min_stack or val <= self.min_stack[-1]: self.min_stack.append(val) def pop(self): if self.stack: val = self.stack.pop() if val == self.min_stack[-1]: self.min_stack.pop() def getMin(self): return self.min_stack[-1] if self.min_stack else None ms = MinStack() ms.push(5) ms.push(3) ms.push(7) ms.pop() print(ms.getMin()) ms.pop() print(ms.getMin())
Remember the min stack keeps track of the smallest values so far.
After pushing 5, 3, 7, the min stack is [5, 3]. Popping removes 7, min remains 3. Next pop removes 3, min becomes 5.
What is the worst-case extra space complexity of a Min Stack that stores minimum values alongside the main stack?
Consider the case when each new element is smaller than all previous ones.
In the worst case, every pushed element is smaller than the previous minimum, so the min stack stores all elements, leading to O(n) extra space.
What error will the following Min Stack pop method cause when popping from an empty stack?
def pop(self):
val = self.stack.pop()
if val == self.min_stack[-1]:
self.min_stack.pop()What happens if self.stack is empty and pop() is called?
Calling pop() on an empty list raises an IndexError.
What is the output of the getMin calls after these operations?
push(2)
push(0)
push(3)
push(0)
getMin()
pop()
getMin()
pop()
getMin()
class MinStack: def __init__(self): self.stack = [] self.min_stack = [] def push(self, val): self.stack.append(val) if not self.min_stack or val <= self.min_stack[-1]: self.min_stack.append(val) def pop(self): if self.stack: val = self.stack.pop() if val == self.min_stack[-1]: self.min_stack.pop() def getMin(self): return self.min_stack[-1] if self.min_stack else None ms = MinStack() ms.push(2) ms.push(0) ms.push(3) ms.push(0) print(ms.getMin()) ms.pop() print(ms.getMin()) ms.pop() print(ms.getMin())
Track the min stack carefully after each pop.
After pushing 2, 0, 3, 0, the min stack is [2, 0, 0]. First getMin() returns 0. Pop removes 0, min stack becomes [2, 0] (still min 0). Pop removes 3 (!= 0), min stack stays [2, 0], getMin() returns 0.
You want to design a Min Stack that uses only one stack and stores the minimum value without extra space for a min stack. Which approach below correctly achieves this?
Think about encoding min info within the stack values themselves.
Option A uses a clever trick storing differences to track min in O(1) space. Option A is inefficient, C uses extra space, D is unrelated.