A stack that also reports its smallest value in constant time. Store each push next to the minimum at that moment, so popping brings the old minimum back.
▼The problem
LeetCode 155 (Medium). Design a stack that supports push, pop, top and getMin, each in O(1) time.
Example: push 5, 3, 7, 2 → getMin = 2; pop → getMin = 3; pop, pop → getMin = 5.
TRY IT ON LEETCODE ▶The solution
class MinStack:
def __init__(self):
self.stack = [] # (val, min) pairs
def push(self, val):
low = min(val, self.stack[-1][1]) if self.stack else val
self.stack.append((val, low))
def pop(self):
self.stack.pop()
def top(self):
return self.stack[-1][0]
def getMin(self):
return self.stack[-1][1]Transcript
Min Stack. Design a stack with four moves: push a value on top, pop the top off, read the top, and get the smallest value in the stack. The catch: all four must run in constant time.
For example, push five, three, seven, then two. The smallest is two. Pop the two, and the minimum is three again. Pop twice more, and only five is left.
The obvious way to find the minimum is to check every crate. Four crates are quick, but with a million crates, every single question costs a million checks. That's order n, not constant.
So keep one variable for the minimum instead. Pushing is easy: keep the smaller value. Five, three, three, two. But now pop the two. The variable still says two, and two is gone. The real minimum is three, and nothing remembers it.
Here's the fix. When a crate goes on the stack, hang a tag on it: the smallest value from that crate down to the floor. That's just the smaller of its own value and the tag on the crate below. The crates underneath never change while it sits there, so its tag never goes stale.
Watch the tags. Five goes first, so its tag is five. Three is smaller, so three gets three. Seven copies the tag below: three. Two gets two. Get min reads the top tag: two. Now pop the two. The crate underneath already says three. Pop seven, pop three, and five's tag says five.
In code, the stack holds pairs: a value and the minimum so far. Push stores the smaller of the value and the top pair's minimum, or just the value on an empty stack. Pop removes the top pair. Top reads its value, and get min reads its minimum.
Every operation touches only the top pair, so each one is constant time. The price is one extra number per crate, so the space is order n.
Every crate remembers the smallest value beneath it, so the answer is always on top. That's Min Stack.