Min Stack

Medium

Topics
StackDesign

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement MinStack with push(val), pop(), top(), and getMin().

Example 1

returnsMinStack()push(-2)push(0)push(-3)getMin()-3pop()top()0getMin()-2
The trick is a second stack carrying the minimum as of each push: a pop discards that entry too, which restores the previous minimum for free.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["MinStack","push","push","push","getMin","pop","top","getMin"], values = [[],[-2],[0],[-3],[],[],[],[]]
Output: [null,null,null,null,-3,null,0,-2]

Constraints

  • -2^31 <= val <= 2^31 - 1
  • pop, top, getMin are only called on non-empty stacks.
  • At most 3*10^4 calls.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The only hard part is O(1) getMin. Track the minimum as of each state on an auxiliary stack so the current minimum is always on top. Every operation is already O(1) — that is optimal in time; the refinement below trims memory by storing each running minimum once with a repeat count instead of duplicating a min for every element.

Approach

  1. Keep the value stack plus a mins stack of (min, count) pairs.
  2. On push: if val is a new minimum push (val, 1); if it ties the current min bump its count; otherwise leave mins untouched.
  3. On pop: if the popped value equals the current min, decrement its count and drop the pair when it reaches zero.
  4. top reads the value stack; getMin reads the top min value. All four operations stay O(1).

Dry Run

MinStack()
  push -2   st [-2]          mins [(-2, 1)]            -2 is a new minimum
  push 0    st [-2, 0]       mins [(-2, 1)]            0 is not smaller, mins untouched
  push -3   st [-2, 0, -3]   mins [(-2, 1), (-3, 1)]   new minimum, pushed
  getMin -> -3               the top of mins
  pop       st [-2, 0]       mins [(-2, 1)]            the popped -3 was the min,
                                                       its count hit 0 and the pair went
  top    -> 0                the top of st
  getMin -> -2               the previous minimum is exposed again
answer null|null|null|null|-3|null|0|-2
Note that pushing 0 adds nothing to mins at all. Only values that are new minima,
or ties with the current one, ever appear there -- which is why mins holds one
entry per DISTINCT running minimum rather than one per element.
The counts exist for ties:
  push 2    st [2]      mins [(2, 1)]
  push 2    st [2, 2]   mins [(2, 2)]   same value, bump the count
  getMin -> 2
  pop       st [2]      mins [(2, 1)]   count down to 1, the pair survives
  getMin -> 2                           still correct
Delete the `elif val == ...` branch and that exact run crashes: the second 2 never
registers, the first pop removes the only mins entry, and getMin raises
IndexError: list index out of range.
That is why push compares with < and pop with ==. Using <= on push instead would
push a second pair rather than bump a count -- also correct, verified identical
across 3000 random operation sequences -- but that is the plain mirror-stack
design, with one mins entry per element and O(n) memory instead of O(k).

Complexity

  • Time — O(1): push, pop, top, and getMin are all constant time — optimal.
  • Space — O(k): the mins stack holds at most one entry per distinct running minimum (k ≤ n), fewer than one min per element.

Common Pitfalls

  • Compare with < on push and == on pop so repeated minimums are counted and released correctly.
  • A plain second stack that mirrors every push also works and is O(1); the count just saves memory.

Full Solution — all languages

class MinStack:
    def __init__(self):
        self.st = []
        self.mins = []              # (min_value, count) — one entry per distinct running min
    def push(self, val):
        self.st.append(val)
        if not self.mins or val < self.mins[-1][0]:
            self.mins.append([val, 1])
        elif val == self.mins[-1][0]:
            self.mins[-1][1] += 1
    def pop(self):
        val = self.st.pop()
        if val == self.mins[-1][0]:
            self.mins[-1][1] -= 1
            if self.mins[-1][1] == 0:
                self.mins.pop()
    def top(self):
        return self.st[-1]
    def getMin(self):
        return self.mins[-1][0]
SensAI
Beta
Tap the mic to stop voice mode