Learn / Stacks and queues

Min stack

Store, next to every value, the smallest value at or below it in the stack. The minimum of the whole stack is then the one stored with the top, so push, pop, top and getMin are all O(1).

How to recognise it

  • A stack must also report its minimum (or maximum) at any time.
  • Every operation must be O(1).
  • A running minimum must survive pops: you need what it was before.

The idea

Each entry is a pair (value, min so far). When you push x, the new minimum is min(x, top's min). Popping takes the pair away, and the minimum stored in the pair below is the correct one again, because it was computed before x arrived.

OperationStack after (value, min)getMin
push -2(-2, -2)-2
push 0(-2, -2) (0, -2)-2
push -3(-2, -2) (0, -2) (-3, -3)-3
pop(-2, -2) (0, -2)-2

A version with less memory

A second stack can hold only the minimums, pushed when x is at most the current minimum and popped when the popped value equals it. It uses less memory when the minimum rarely changes, but the pair version is simpler to get right.

Common mistakes

  • In the two-stack version, pushing to the minimum stack only when x is strictly smaller, so duplicate minimums are lost.
  • Comparing boxed Integer values with == in Java.

Problems

0 of 1 solved

Check yourself

You push 5, 3, 7. What is stored with 7?

After popping 7 and 3 from that stack, what is the minimum?

Why can one variable not track the minimum?