TRT
Sign in
mediumFoundationsLeetCode#stack of pairs#running minimum

Min stack

Design a stack that also returns its minimum element in O(1), even after pops, by storing the running minimum with each item.

The Runtime Theory Team1 min read
Taught inStacks and the LIFO ruleA stack only lets you touch its most recent item. That restriction makes it cheap to build on an array, and it is exactly what nested structure, undo and matching brackets need.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

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

out-3, 0, -2

inpush(2), push(2), getMin(), pop(), getMin()

out2, 2

inpush(5), getMin()

out5

Design a stack that supports push, pop, top and getMin, each in O(1) time.

Before you code

One variable holding the minimum breaks as soon as you pop the minimum: what was the minimum before it? The stack needs to remember the minimum as it was at every depth.

Hints

  1. Push pairs: (value, min(value, current_min)). The top pair's second element is always the minimum of the whole stack.
  2. Popping a pair automatically restores the previous minimum, because the pair below stored it.
  3. Space-saving variant: keep a second stack that only receives a value when it is less than or equal to its own top. Why must equal values be pushed too?

Production & complexity notes

When solving Min stack on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Stacks and the LIFO rule to reinforce the underlying pattern.

What it practices

Storing a summary of everything beneath each entry, from Stacks and the LIFO rule.

Not started

Sign in to save your learning progress.

Sign in to save