Min Stack

MediumStack · Design🧩 StackLeetCode #155 ↗Updated

Problem

Design a class MinStack that behaves like a normal integer stack (push, pop, top) and also answers getMin() — the smallest value currently on the stack. Every operation should run in O(1) time.
Inputpush(-2) push(0) push(-3)OutputgetMin() = -3
Inputpop() top() getMin()Output0, -2

-231 ≤ val ≤ 231-1  ·  pop/top/getMin only on a non-empty stack  ·  ≤ 3·104 calls  ·  each op O(1)

Try it yourself

Java
class MinStack {
    public void push(int val) {
        
    }

    public void pop() {
        
    }

    public int top() {
        
    }

    public int getMin() {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A stack only changes at the top, so the minimum below any element never changes while that element is on the stack. Record the “min so far” at push time and restore it at pop time.
PatternStack

Instinct Things resolve in reverse order of arrival (brackets, adjacent pairs, nested expressions) - push now, pop when its partner shows up.

Memory hack Last in, first out - like a pile of plates, you only ever touch the one on top; every closer pops its opener.

Open the Stack guide →

Approaches

Brute ForcePlain Stack, Scan for Min

Time O(1) push/pop/top, O(n) getMinSpace O(n)

Keep an ordinary stack and compute the minimum on demand by iterating over every element. Correct, because the stack always holds exactly the live values.

Java
class MinStack {
    private final Deque<Integer> stack = new ArrayDeque<>();

    public void push(int val) { stack.push(val); }

    public void pop() { stack.pop(); }

    public int top() { return stack.peek(); }

    public int getMin() {
        int min = Integer.MAX_VALUE;
        for (int x : stack) min = Math.min(min, x);
        return min;
    }
}

Simplest possible, but getMin is linear — violates the O(1) requirement.

At a glance

LevelApproachTimeSpace
Brute ForcePlain Stack, Scan for MinO(1) push/pop/top, O(n) getMinO(n)
BetterStack of (value, minSoFar) PairsO(1) all opsO(n)
OptimalSingle Stack + min VariableO(1) all opsO(n)
Common pitfalls
  • Using val < min instead of ≤ — duplicate minimums lose the old min on pop.
  • A single min field with no history — cannot recover after popping the min.
  • Storing val - min in an int — overflows at ±231; needs long.
Interview tips
  • Start from the O(n) getMin scan, then ask: what does each element need to remember?
  • Explain why the min below an element is frozen while it is on the stack.
  • Offer the space trade-off: pairs (simple) vs markers only on min change.
Pattern
Augmented stack → track an aggregate (min/max) of the stack in O(1) per operation.
My notes saved in this browser