Typorithm · medium

Min Stack

min-stackstacks-queuesauxiliary-stackrunning-minconstant-time
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Min Stack

0%

Stacks & Queues

Keep a parallel stack of running minimums so getMin is O(1) at every depth.

Tracking a single min variable breaks when that min is popped off.

A parallel stack records the minimum present at each level, pushed and popped in lockstep.

The top of that min stack is the current minimum, so getMin is constant time.

01

Parallel min stack per level.

02

Push min(val, prevMin).

03

getMin reads the min stack top.

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

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

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

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

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

Read the implementation

Connect each part of the code to the concept before you type.

1. Min history

A parallel stack stores the minimum at each depth.

this.mins = []

2. New running min

The min so far is the smaller of val and the prior min.

Math.min(val, this.mins[this.mins.length - 1])

3. Pop both

Removing a value also removes its recorded min.

this.mins.pop()

4. O(1) min

The top of the min stack is always the current minimum.

return this.mins[this.mins.length - 1]

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Min Stack: Lesson & Practice · Typorithm | ApplyDjinn