sagelearnai

Min Stack

Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #155

Design a stack class MinStack that supports, all in O(1) time:

  • push(val): push a value,
  • pop(): remove the top value,
  • top(): return the top value,
  • getMin(): return the smallest value currently in the stack.

pop, top and getMin are only called on non-empty stacks.

Example

text
push(5), push(2), push(7), getMin() → 2, pop(), top() → 2, pop(), getMin() → 5

The tests call your class in LeetCode's design format: a list of operations and their arguments.

Hints

  1. Keeping a single min variable fails after the minimum is popped. What was the min before it was pushed?
  2. Store, with every element, the minimum of the stack at the time it was pushed.

Approach

Push pairs (val, min(val, currentMin)). The minimum of the whole stack is always the second field of the top pair, and popping automatically restores the previous minimum. Every operation is O(1). (An alternative uses a second stack that only stores new minimums.)

Complexity

Time: O(1) per operation. Space: O(n).

Python solution
class MinStack:
    def __init__(self):
        self.st = []                  # (value, min so far)

    def push(self, val):
        m = val if not self.st else min(val, self.st[-1][1])
        self.st.append((val, m))

    def pop(self):
        self.st.pop()

    def top(self):
        return self.st[-1][0]

    def getMin(self):
        return self.st[-1][1]
JavaScript solution
class MinStack {
  constructor() { this.st = []; }
  push(val) {
    const m = this.st.length ? Math.min(val, this.st[this.st.length - 1][1]) : val;
    this.st.push([val, m]);
  }
  pop() { this.st.pop(); }
  top() { return this.st[this.st.length - 1][0]; }
  getMin() { return this.st[this.st.length - 1][1]; }
}