Min Stack
A stack that also tells you its smallest value
DSA, Medium, Stack
Which structure or algorithm, and what does it cost.
Design a class MinStack that works like a stack and can also report its smallest value. It has four operations. push(x) puts x on top. pop() removes the top value. top() returns the top value. get_min() returns the smallest value now in the stack. Every operation must take constant time. The input is a list of operation strings. The output lists the result of each top and get_min call, in order. You only write the class. The operation list shows the order of the calls.
Examples
Constraints
- 1 <= number of operations <= 100,000.
- Each pushed value is a whole number between -1,000,000,000 and 1,000,000,000.
pop,topandget_minare only called when the stack holds at least one value.
Your answer must contain
- The simple method and why it is too slow; the method; code; time and memory cost; a hand trace of example 1.
Target Aim for O(1) time for every operation and O(n) memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
After a pop, an old minimum may come back. Ask what you would need to remember so that finding it costs no search.
Hint 2 the approach
The smallest value changes only at a push or a pop. What could you save at each push so a pop brings the old answer back?
Hint 3 the key step
Store a second number with every pushed value, describing the stack from the bottom up to it. Which number lets get_min only read the top?
Walkthrough
Full walkthrough brute force to best
Brute force
Keep a plain list. For get_min, scan the whole list for the smallest value. Push, pop and top are O(1), but each get_min costs O(n). With 50,000 pushes followed by 50,000 get_min calls, that is about 2.5 billion steps.
Best method
Store each item as a pair: the value, and the smallest value from the bottom of the stack up to and including that item. When you push x, the new smallest is x if the stack is empty. Otherwise it is the smaller of x and the saved smallest of the item below. A pop removes the top pair and exposes the pair below, which still holds its own correct smallest. So the saved number on top always describes exactly the values now in the stack. top reads the first number and get_min reads the second, both in constant time.
Hand trace
Run on push 6, push 2, push 9, get_min, pop, pop, get_min, top. Push 6: the stack is empty, so the pair is (6, 6). Stack [(6, 6)]. Push 2: the smaller of 2 and 6 is 2. Stack [(6, 6), (2, 2)]. Push 9: the smaller of 9 and 2 is 2. Stack [(6, 6), (2, 2), (9, 2)]. get_min reads 2 from the top pair. Two pops remove (9, 2) and then (2, 2). Stack [(6, 6)]. get_min reads 6. top reads 6. The output is [2, 6, 6].
Code
class MinStack:
def __init__(self):
self.items = [] # pairs: (value, smallest value from the bottom up to here)
def push(self, x):
low = min(x, self.items[-1][1]) if self.items else x
self.items.append((x, low))
def pop(self):
self.items.pop()
def top(self):
return self.items[-1][0]
def get_min(self):
return self.items[-1][1]Time and memory
Every operation is O(1): each does one append, one removal or one read. Memory is O(n), because the stack holds one pair per value.
Common mistakes
- Keeping a single variable for the minimum. When that minimum is popped, the variable is wrong and the next one needs a scan.
- Forgetting the empty case on the first push. There is no item below to compare with, so the value is its own minimum.
- Returning the saved minimum from
top, or the value fromget_min. The two numbers in a pair mean different things. - In the two-stack version, saving a new minimum only when it is strictly smaller. A second copy of the minimum must be saved too, or one pop removes the minimum while a copy is still in the stack. Example 2 checks this.