AniUI Academy

A stack that reports its minimum in O(1)

mediumData Structures+250 XPPractice

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 smallest
const s = new MinStack();
s.push(5); s.push(3);
s.pop();     // 3
s.min();     // 5 — minimum restored after popping it

Popping 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() and peek() return undefined on an empty stack.
  • min() must not scan the whole stack on each call.
  • push returns 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.min for Math.max and you get an O(1) max-stack with the same shape.
Asked atAmazonMicrosoft

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.