Problem Statement
Min Stack
Build a stack that can do four things fast: push (add an item on top), pop (remove the top item), top (peek at the top item), and getMin (tell you the smallest item still in the stack). The catch is that getMin has to be instant, no matter how many items are inside. A stack is like a pile of plates: you add a plate to the top and take a plate from the top, so the last plate you put on is the first one you take off. That order is called last in, first out. The tricky part here is the minimum. If we searched the whole pile every time someone asked "what is the smallest?", that would be slow. We need a trick to know the answer right away.
Signals to notice
Brute force first
Scan the entire stack for minimum on each getMin call. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
Use a second stack that tracks the current minimum at each level — for all operations. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on ops=["MinStack","push","push","push","getMin","pop","top","getMin"], args=[[],[-2],[0],[-3],[],[],[],[]]
init -> stack=[], min_stack=[] (constructor, returns null) push(-2): min(-2)= -2 -> stack=[-2], min_stack=[-2] push(0): min(0,-2)= -2 -> stack=[-2,0], min_stack=[-2,-2] push(-3): min(-3,-2)= -3 -> stack=[-2,0,-3], min_stack=[-2,-2,-3] getMin(): min_stack.top -> -3 (output) pop(): drop tops -> stack=[-2,0], min_stack=[-2,-2] top(): stack.top -> 0 (output) getMin(): min_stack.top -> -2 (output) => results [null,null,null,null,-3,null,0,-2]
What must stay true
The min stack always has the same height as the main stack; its top is the current minimum. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
push(val): stack.append(val) cur_min = val if min_stack empty else min(val, min_stack.top) min_stack.append(cur_min) pop(): stack.pop(); min_stack.pop() top(): return stack.top getMin(): return min_stack.top # O(1)
Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Only pushing to min stack when a new minimum is found — push on every operation to keep stacks synchronized. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.