☰ All problems

Min Stack

MediumStackDesign

A budgeting app keeps the history of an account balance on a stack. Each transaction pushes the new balance on top, and undo pops the most recent one. The app also warns users about the lowest balance in the current history, and that lookup has to be as cheap as every other operation.

Implement the MinStack class so that every method runs in O(1) time:

  • MinStack() starts with an empty history.
  • push(val) pushes the balance val on top.
  • pop() removes the most recent balance (the undo).
  • top() returns the most recent balance without removing it.
  • getMin() returns the smallest balance currently in the history.

Balances are integers and can be negative (an overdraft). The tests call the methods one after another and never call pop, top or getMin on an empty history.

Example 1
Input: ["MinStack","push","push","push","push","getMin","pop","getMin","pop","top","pop","getMin"]
[[],[50],[20],[70],[10],[],[],[],[],[],[],[]]
Output: [null,null,null,null,null,10,null,20,null,20,null,50]

Explanation: The lowest balance is 10 until that transaction is undone, then 20. Once 70 and 20 are undone as well, only 50 remains.

Example 2
Input: ["MinStack","push","push","push","getMin","pop","pop","getMin","top"]
[[],[-5],[-5],[3],[],[],[],[],[]]
Output: [null,null,null,null,-5,null,null,-5,-5]

Explanation: The overdraft of -5 was pushed twice. Undoing 3 and one copy of -5 still leaves -5 as both the top and the minimum.

Constraints

  • Every pushed value fits in a 32-bit signed integer.
  • A single test makes no more than 30,000 method calls.
  • pop, top and getMin are only called while the history is non-empty.
💡 Hint 1

The minimum can change when you pop. Can you remember what the minimum was at every depth of the stack?

💡 Hint 2

Store pairs (value, minimum so far), or keep a second stack of minimums.

class MinStack {
  constructor() {

  }

  /** @param {number} val */
  push(val) {

  }

  pop() {

  }

  /** @return {number} */
  top() {

  }

  /** @return {number} */
  getMin() {

  }
}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc