Skip to content

Min Stack

MediumStack
Decode it first. Clues, constraints, pattern and plan before any code.

Build a class MinStack that works like a normal stack but can also report its smallest value in O(1) time. Every method must run in O(1).

  • push(val) adds val to the top.
  • pop() removes the top value and returns it.
  • top() returns the top value without removing it.
  • get_min() in Python, getMin() in TypeScript, returns the smallest value currently in the stack.
s = MinStack()
s.push(-2); s.push(0); s.push(-3)
s.get_min()   →  -3
s.pop()       →  -3
s.top()       →  0
s.get_min()   →  -2

Constraints

  • -2^31 <= val <= 2^31 - 1
  • pop, top and get_min are only called on a non-empty stack.
  • At most 3 * 10^4 calls are made in total.