Min Stack
A stack that also returns its minimum in O(1) — no scanning. The trick is to carry the running minimum alongside each element. Replay a sequence of push/pop/top/getMin operations and return the outputs. Solve it in Python or TypeScript, with hidden tests.
The problem
Design a stack that supports push(x), pop(), top(), and getMin() — each in O(1) time. You are given a list of ops such as ["push",5], ["pop"], ["top"], ["getMin"]. Apply them in order and return the list of values produced by the read operations (top and getMin), in order.
ops = [["push",5],["push",3],["getMin"],["pop"],["getMin"],["top"]][3, 5, 5]ops = [["push",2],["push",2],["getMin"],["pop"],["getMin"]][2, 2]- Every
pop/top/getMinis called on a non-empty stack. - All four operations must be O(1) — do not scan the stack to find the minimum.
- Duplicate minimum values must survive a single pop (the min only rises once all copies are gone).
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.
Implement min_stack_ops(ops): maintain a stack plus a parallel "min so far" stack. On push, record min(x, current_min); on pop, drop both. Collect the outputs of every top and getMin.
- The naive getMin scans the stack — O(n). To get O(1), store the minimum as of each push next to the value.
- Keep a second stack
mins: when you pushx, pushmin(x, mins[-1])(or justxif empty). - On pop, pop both stacks together so
mins[-1]always reflects the current stack. - This is why duplicates matter: pushing the min twice puts it on
minstwice, so one pop does not lose it.
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.