Min stack
Medium TimeO(1) per op SpaceO(n)
Build a stack that can push, pop, and also report the smallest value it currently holds — all three in constant time, so scanning for the minimum when asked does not count. Popping has to restore whatever the minimum was before the popped value arrived, and duplicate values are allowed, each accounted for separately.
Examples
Example 1
- Input
- demo()
- Output
- Push 5, 2, 7 and the smallest is
[2,5]2; pop twice, only the 5 is left, and it is5.
Example 2
- Input
- makeMinStack().getMin()
- Output
- A stack holding nothing has no smallest value to report.
undefined
The Code
function makeMinStack() {
const values = [];
const mins = [];
return {
push(v) {
values.push(v);
const currentMin = mins.length === 0 ? v : Math.min(v, mins[mins.length - 1]);
mins.push(currentMin);
return values.length;
},
pop() {
mins.pop();
return values.pop();
},
getMin() {
return mins[mins.length - 1];
}
};
}
function demo() {
const s = makeMinStack();
s.push(5);
s.push(2);
s.push(7);
const before = s.getMin();
s.pop();
s.pop();
return [before, s.getMin()];
}
demo();Done
More like this
All stacks & queues examples (8) →- Valid parentheses Push every opener; every closer must match the top.
- Evaluate RPN Numbers go on the stack; an operator eats the top two.
- Next greater element A monotonic stack of indices still waiting for something bigger.
- Daily temperatures How many days until it gets warmer — same stack, distance instead.
- Queue from stacks Two LIFO stacks make one FIFO queue — reversal cancels out.
- Largest rectangle A bar’s rectangle ends where a shorter bar appears on either side.