Min Stack

medium

Design a stack that supports push, pop, top, and retrieving the minimum element — all in O(1) time:

  • push(x) — push x onto the stack.
  • pop() — remove the element on top.
  • top() — return the top element.
  • getMin() — return the minimum element currently in the stack.

pop, top, and getMin are only called on a non-empty stack.

Hints

getMin in O(1) means you can't scan the stack — store the minimum somewhere.
Alongside each element, remember the minimum of the stack up to that element.
Push both (min of new value and previous min) and pop both together.

Common doubts

A single min variable can't be restored when you pop the current minimum. Storing the running minimum per element lets pop reveal the previous minimum instantly.
min(x, current minimum) — so the top of mins is always the minimum of the whole stack.
Yes — store pairs (value, min-so-far), or use an encoding trick that stashes the old minimum when a new minimum is pushed. The two-stack version is the clearest.

Interview follow-ups

Keep a parallel maxes stack with max(x, previous max) — the exact mirror.
Push onto the mins stack only when a new value is <= the current min, and pop it only when the popped value equals the current min — saving space when minimums repeat rarely.

Fun facts

  • Min Stack is the textbook example of 'augment your structure with the query's answer'.
  • The same idea gives O(1) min/max over a sliding window when combined with the two-stack queue — a min-queue.

Asked at

AmazonGoogleMicrosoftBloomberg
Frequently Sometimes Occasionally
Example 1
Input: push(-2), push(0), push(-3), getMin(), pop(), top(), getMin()
Output: -3, 0, -2
getMin returns -3, then after popping -3, top is 0 and getMin is -2.
Example 2
Input: push(1), getMin(), top()
Output: 1, 1
With one element, both getMin and top return 1.
Constraints

- -2^31 <= x <= 2^31 - 1 - At most 3 * 10^4 operations - pop/top/getMin only on a non-empty stack

Solve this problem →