Min Stack

Difficulty: Medium

Design a stack that supports push, pop, top, and getMin (the smallest value in the stack). All four operations must run in constant time, no matter how big the stack gets.

Examples

Input: push(-2), push(0), push(-3), getMin(), pop(), top(), getMin()
Output: getMin() -> -3, then after pop() the stack holds -2, 0; top() -> 0, getMin() -> -2

After the three pushes, the stack holds -2, 0, -3 (bottom to top), so the minimum is -3. Popping removes -3; now the top is 0, and the smallest of what remains (-2 and 0) is -2.

Input: push(1), push(2), getMin(), pop(), getMin()
Output: getMin() -> 1, then after pop() removes 2, getMin() -> 1

1 stays the minimum throughout, since 2 gets popped off without ever having been the smallest.

Constraints

  • pop, top, and getMin are only ever called when the stack is non-empty.

  • At most 3 * 10^4 calls total will be made to push/pop/top/getMin.

Approach

Tracking the minimum on push is easy: compare against a running minimum. Popping is the hard part. If you pop the current minimum, you need the minimum from before it was pushed, and a single variable can't tell you.

Keep a second stack, the min-stack. Each entry records the minimum at the moment that element was pushed. Every push and pop touches both stacks, so the top of the min-stack is always the current minimum.

Solutions

Brute Force — Scan for the Minimum

Use a plain array as the stack. push, pop, and top are O(1), but getMin() scans the whole stack on every call.

class MinStack {
  constructor() {
    this.stack = [];
  }

  push(val) {
    this.stack.push(val);
  }

  pop() {
    this.stack.pop();
  }

  top() {
    return this.stack[this.stack.length - 1];
  }

  getMin() {
    return Math.min(...this.stack);
  }
}

Time: push/pop/top: O(1), getMin: O(n) · Space: O(n)

Optimal — Auxiliary Min Stack

Keep a second stack where each entry is the minimum right after that push. Popping both stacks together leaves the correct minimum on top of the min-stack.

class MinStack {
  constructor() {
    this.stack = [];
    this.minStack = [];
  }

  push(val) {
    this.stack.push(val);
    const currentMin =
      this.minStack.length === 0
        ? val
        : Math.min(val, this.minStack[this.minStack.length - 1]);
    this.minStack.push(currentMin);
  }

  pop() {
    this.stack.pop();
    this.minStack.pop();
  }

  top() {
    return this.stack[this.stack.length - 1];
  }

  getMin() {
    return this.minStack[this.minStack.length - 1];
  }
}

Time: O(1) for push, pop, top, and getMin · Space: O(n), for the extra min-tracking stack