A stack that reports its minimum in O(1)
Imagine a chart tool where the user pushes and pops data points and the axis label must always show the current smallest value. Recomputing the minimum on every change is O(n) each time; a min stack gives it to you in constant time.
Implement a MinStack class holding numbers. It is constructed with no arguments and starts empty. push(value) adds a number on top and returns the new size. pop() removes and returns the top number, or undefined when empty. peek() returns the top number without removing it, or undefined when empty. min() returns the smallest number currently in the stack, or undefined when empty, without scanning the whole stack. size() returns how many numbers are held.
The minimum must stay correct as values are popped: if the smallest value is removed, min() reports the next smallest of what remains. Duplicate values count separately, so pushing the same minimum twice and popping once still leaves that minimum in place.
Examples
const s = new MinStack();
s.push(5); s.push(3); s.push(7);
s.min(); // 3
s.peek(); // 7
s.pop(); // 7
s.min(); // 3 — still the smallestconst s = new MinStack();
s.push(5); s.push(3);
s.pop(); // 3
s.min(); // 5 — minimum restored after popping itPopping the current minimum reveals the next smallest below it.
What it has to do
min()returns the smallest value currently in the stack.min()stays correct after values are popped, including duplicates of the minimum.min(),pop()andpeek()returnundefinedon an empty stack.min()must not scan the whole stack on each call.pushreturns the new size.
Notes
- Every operation is O(1), including
min(). The trade-off is O(n) extra space for the parallel stack of running minimums. - The parallel-stack trick generalises: swap
Math.minforMath.maxand you get an O(1) max-stack with the same shape.
Stuck? The javascript course covers everything this challenge needs.
- 1.reports the smallest value while pushing
- 2.restores the previous minimum after popping
- 3.counts duplicate minimums separately
- 4.an empty stack reports undefined everywhere
- 5.handles negative values
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.