Skip to content

Min Stack

MediumLeetCode #155Time O(1)Space O(n)

Build a stack class with push, pop, top and getMin. Every operation must run in O(1), including getMin, which returns the smallest value currently in the stack.

push(-2), push(0), push(-3)
getMin() -> -3
pop()
top() -> 0, getMin() -> -2

Scanning the stack for the minimum on every getMin is O(n). Keeping one global min variable breaks on pop: if you remove the minimum, you don’t know the next one.

The fix is to notice the minimum only depends on what is below each element, and that never changes while the element is in the stack. So store with every value the minimum of the stack up to and including it, as a (value, minSoFar) pair. getMin reads the top pair. pop throws the pair away, and the previous pair already holds the right minimum.

Show solutionHide solution
class MinStack:
def __init__(self):
self.stack = [] # (value, minimum of everything at or below it)
def push(self, val: int) -> None:
low = min(val, self.stack[-1][1]) if self.stack else val
self.stack.append((val, low))
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1][0]
def get_min(self) -> int:
return self.stack[-1][1]
  • Time: O(1) — push, pop, top and getMin each touch only the top of the stack.
  • Space: O(n) — one pair per element, so about twice the memory of a plain stack.
  • A single min variable is wrong. It can’t roll back after popping the minimum.
  • Duplicate minimums. Pushing 1, 1 then popping once must still report 1. Storing the min per element handles this. A separate min-stack must push on <=, not <.
  • Empty-stack calls. LeetCode guarantees pop, top and getMin are only called on a non-empty stack, so no guard is needed. Say so if asked.

Same idea, plus popMax, which removes the maximum wherever it sits. The trick: the pair trick handles peekMax, but popMax must remove from the middle. Simple answer: pop into a temporary stack until you hit the max, then push everything back (O(n)). Faster: a doubly linked list plus a sorted map for O(log n).

Implement Queue using Stacks (LeetCode 232)

Section titled “Implement Queue using Stacks (LeetCode 232)”

Build a FIFO queue from two stacks. The trick: push onto an input stack. When you need to pop or peek and the output stack is empty, pour the whole input stack into it, which reverses the order. Each element moves at most twice, so operations are amortized O(1).

Evaluate Reverse Polish Notation (LeetCode 150)

Section titled “Evaluate Reverse Polish Notation (LeetCode 150)”

Evaluate an expression like ["2","1","+","3","*"]. The trick: push numbers; on an operator pop two operands, apply it, push the result. Note the order: the first pop is the right operand. Mind that division truncates toward zero.