Coding problem · Medium · Stack

Min Stack

Medium Algorithms & data structures Seen at Amazon, Bloomberg, Microsoft

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

  • push(val) pushes val.
  • pop() removes the top element.
  • top() returns the top element.
  • getMin() returns the minimum element in the stack.

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

Example 1

Input: ["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output: [null,null,null,null,-3,null,0,-2]

Hints

Hint 1

Store, alongside each value, the minimum of the stack at the time it was pushed.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(1) per operation · Space O(n)

Push pairs (value, minSoFar) where minSoFar = min(value, previous pair's min). The top pair always holds the current minimum, and popping restores the previous minimum automatically.

Reference solution

class MinStack {
  constructor() {
    this.items = []; // [value, minSoFar]
  }
  push(val) {
    const min = this.items.length ? Math.min(val, this.items[this.items.length - 1][1]) : val;
    this.items.push([val, min]);
  }
  pop() {
    this.items.pop();
  }
  top() {
    return this.items[this.items.length - 1][0];
  }
  getMin() {
    return this.items[this.items.length - 1][1];
  }
}

Common mistakes

  • Keeping a single min variable — you can't recover the previous minimum after popping it.