Skip to content
StackDecode
Stacks & queuesAnimated

Min Stack

Keep a second stack of running minimums.

Time

O(1)

Extra space

O(n)

Use it for

Getting the minimum in constant time.

How it works

  1. A normal stack cannot tell you its minimum without scanning.
  2. Keep a second stack alongside it: when pushing x, also push min(x, current minimum).
  3. Popping removes from both stacks, so the minimum is always the top of the helper stack.
  4. push, pop and getMin are all O(1).

Watch it run

Loading animation…