☰ All problems

7. Min Stack

MediumStackDesign

Design a stack that supports push, pop, top and retrieving the minimum element, all in O(1) time.

Implement the MinStack class:

  • MinStack() creates an empty stack.
  • push(val) pushes val.
  • pop() removes the top element.
  • top() returns the top element.
  • getMin() returns the smallest element in the stack.

Tests call the methods in sequence; pop, top and getMin are only called on a non-empty stack.

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

Explanation: After pushing -2, 0, -3 the minimum is -3. Popping -3 leaves 0 on top and -2 as the minimum.

Constraints

  • -2^31 <= val <= 2^31 - 1
  • At most 3 * 10^4 calls in total
💡 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