Practice · Stack · 3 of 3

Stack with Minimum

Write a class MinStack, a stack of integers with four methods:

  • push(val) puts val on top.
  • pop() removes the top item.
  • top() returns the top item.
  • getMin() returns the smallest item currently on the stack.

Every method must take constant time, so getMin can't search the stack. pop, top and getMin are only called when the stack isn't empty.

Each test is a list of calls, starting with the constructor; the expected answer lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Calls
MinStack(), push(5), push(2), push(8), getMin(), pop(), top(), getMin()
Returns
[null, null, null, null, 2, null, 2, 2]

Example 2

Calls
MinStack(), push(3), push(1), pop(), getMin()
Returns
[null, null, null, null, 3]
Popping 1 brings back the minimum from before it was pushed.

Constraints

  • Values are between −2³¹ and 2³¹ − 1.
  • A test makes at most 3 × 10⁴ calls.
Brush up firstStack visualiser