1. Min history
A parallel stack stores the minimum at each depth.
this.mins = []Typorithm · medium
Step 1 of 8 · intro card
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.
Parallel min stack per level.
Push min(val, prevMin).
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];
}
}Connect each part of the code to the concept before you type.
A parallel stack stores the minimum at each depth.
this.mins = []The min so far is the smaller of val and the prior min.
Math.min(val, this.mins[this.mins.length - 1])Removing a value also removes its recorded min.
this.mins.pop()The top of the min stack is always the current minimum.
return this.mins[this.mins.length - 1]Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.