Min Stack
The problem
Section titled “The problem”Build a stack class with push, pop, top and getMin. Every operation must run in
O(1), including getMin, which returns the smallest value currently in the stack.
push(-2), push(0), push(-3)getMin() -> -3pop()top() -> 0, getMin() -> -2Key insight
Section titled “Key insight”Scanning the stack for the minimum on every getMin is O(n). Keeping one global
min variable breaks on pop: if you remove the minimum, you don’t know the next one.
The fix is to notice the minimum only depends on what is below each element, and
that never changes while the element is in the stack. So store with every value the
minimum of the stack up to and including it, as a (value, minSoFar) pair. getMin reads
the top pair. pop throws the pair away, and the previous pair already holds the
right minimum.
Show solutionHide solution
class MinStack: def __init__(self): self.stack = [] # (value, minimum of everything at or below it)
def push(self, val: int) -> None: low = min(val, self.stack[-1][1]) if self.stack else val self.stack.append((val, low))
def pop(self) -> None: self.stack.pop()
def top(self) -> int: return self.stack[-1][0]
def get_min(self) -> int: return self.stack[-1][1]export class MinStack { private stack: [number, number][] = []; // [value, minimum of everything at or below it]
push(val: number): void { const low = this.stack.length ? Math.min(val, this.stack[this.stack.length - 1][1]) : val; this.stack.push([val, low]); }
pop(): void { this.stack.pop(); }
top(): number { return this.stack[this.stack.length - 1][0]; }
getMin(): number { return this.stack[this.stack.length - 1][1]; }}import java.util.ArrayDeque;import java.util.Deque;
class MinStack { private final Deque<int[]> stack = new ArrayDeque<>(); // {value, minimum at or below it}
public void push(int val) { int low = stack.isEmpty() ? val : Math.min(val, stack.peek()[1]); stack.push(new int[] {val, low}); }
public void pop() { stack.pop(); }
public int top() { return stack.peek()[0]; }
public int getMin() { return stack.peek()[1]; }}Complexity
Section titled “Complexity”- Time: O(1) — push, pop, top and getMin each touch only the top of the stack.
- Space: O(n) — one pair per element, so about twice the memory of a plain stack.
Watch out for
Section titled “Watch out for”- A single
minvariable is wrong. It can’t roll back after popping the minimum. - Duplicate minimums. Pushing
1,1then popping once must still report1. Storing the min per element handles this. A separate min-stack must push on<=, not<. - Empty-stack calls. LeetCode guarantees
pop,topandgetMinare only called on a non-empty stack, so no guard is needed. Say so if asked.
Variations
Section titled “Variations”Max Stack (LeetCode 716, premium)
Section titled “Max Stack (LeetCode 716, premium)”Same idea, plus popMax, which removes the maximum wherever it sits. The trick: the
pair trick handles peekMax, but popMax must remove from the middle. Simple answer: pop
into a temporary stack until you hit the max, then push everything back (O(n)). Faster:
a doubly linked list plus a sorted map for O(log n).
Implement Queue using Stacks (LeetCode 232)
Section titled “Implement Queue using Stacks (LeetCode 232)”Build a FIFO queue from two stacks. The trick: push onto an input stack. When you need to pop or peek and the output stack is empty, pour the whole input stack into it, which reverses the order. Each element moves at most twice, so operations are amortized O(1).
Evaluate Reverse Polish Notation (LeetCode 150)
Section titled “Evaluate Reverse Polish Notation (LeetCode 150)”Evaluate an expression like ["2","1","+","3","*"]. The trick: push numbers; on an
operator pop two operands, apply it, push the result. Note the order: the first pop is the
right operand. Mind that division truncates toward zero.