Min Stack

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write a class MinStack, made with new MinStack(). push(x) puts the number x on top; pop() removes the top number and returns it; top() returns the top number without removing it; and getMin() returns the smallest number on the stack. pop, top and getMin are only called when the stack isn't empty. Each should take constant time. For example, after push(3), push(1) and push(2), getMin() is 1, and after two pops it's 3. The checks make about 500,000 calls on a stack up to 100,000 deep, so searching it for the smallest is too slow.

Your code must pass

  • Pushes, pops and shows the top
  • Returns the smallest number
  • Updates the smallest number after a pop
  • Keeps the smallest number when it was pushed twice
  • Is fast enough for 100,000 numbers