Browse curriculum

Min Stack

Design a stack that supports retrieving the minimum element in constant time.

Problem Understanding

Design a stack that supports push, pop, top, and getMin operations, all in O(1) time.

  • push(val): Pushes element val onto stack.
  • pop(): Removes element on top of stack.
  • top(): Gets the top element.
  • getMin(): Retrieves minimum element in the stack.

Algorithm Strategy

A standard stack gives O(1) push/pop, but finding the minimum usually takes O(N). To get O(1) min, we trade Space for Time.

Strategy:
Maintain a second stack, minStack. Whenever we push a value x onto the mainStack, we also push min(x, minStack.top()) onto the minStack. The top of minStack always represents the minimum of the mainStack at that height.

Interactive Visualization

Visualize two stacks growing in parallel. The MinStack tracks the minimum value seen 'so far'.

Dry Run

Ops: push 2, push 0, push 3, getMin, pop, top, getMin

Op stack minStack Returns
push 2 [2] [2] -
push 0 [2, 0] [2, 0] -
push 3 [2, 0, 3] [2, 0, 0] (min(3, 0) = 0) -
getMin [2, 0, 3] [2, 0, 0] 0
pop [2, 0] [2, 0] -
top [2, 0] [2, 0] 0
getMin [2, 0] [2, 0] 0

Edge Cases & Common Mistakes

  • Empty Stack: getMin on empty stack (usually invalid op by problem statement, but good to check).
  • Duplicate Min: If we push 0 then another 0, minStack should store both so when one pops, the other remains.

Solution

Using two stacks.

Min Stack Code
1var MinStack = function() {
2 this.stack = [];
3 this.minStack = [];
4};
5
6MinStack.prototype.push = function(val) {
7 this.stack.push(val);
8 this.minStack.push(this.minStack.length === 0 ? val : Math.min(val, this.minStack[this.minStack.length - 1]));
9};
10
11MinStack.prototype.pop = function() {
12 this.stack.pop();
13 this.minStack.pop();
14};
15
16MinStack.prototype.top = function() {
17 return this.stack[this.stack.length - 1];
18};
19
20MinStack.prototype.getMin = function() {
21 return this.minStack[this.minStack.length - 1];
22};

The approach, step by step

  1. Push to both

    Push the value, and push min(value, minStack top) onto minStack.

  2. Pop from both

    Pop the value and its minimum entry together.

  3. Read the tops

    top reads the value stack; getMin reads minStack’s top.

Frequently asked questions

How does Min Stack get the minimum in O(1)?

Alongside the values, keep a second stack where each push adds min(value, current minimum). Its top is always the minimum of the whole stack, so getMin just reads it.


What happens with duplicate minimum values?

Each push adds its own minimum entry, so two pushes of the same minimum leave two copies. Popping one still leaves the other, and getMin stays correct.


What is the space cost?

O(n) extra: one minimum entry per value. Every operation is O(1) time.

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description