Min Stack
Design a stack that supports push, pop, top, and getMin in O(1) time. Think about: How can you track the minimum efficiently? Hint: Consider using an auxiliary structure to track minimums. Example: push(-2), push(0), push(-3) get_min() → -3 pop() top() → 0 get_min() → -2
Min Stack is all about maintaining a clear stack meaning as you process input. Interviewers love it because it reveals your stack invariants and your edge-case discipline. The classic mistake is not being clear about what your stack represents at each step.
Examples
You write
MinStack: push(val: int), pop(), top(), get_min()
Example 1
- Input
- MinStack(), push(-2), push(0), push(-3), getMin() => -3, pop(), top() => 0, getMin() => -2
- returns
- [-3, 0, -2]
Example 2
- Input
- MinStack(), push(1), push(2), push(0), getMin() => 0, pop(), getMin() => 1
- returns
- [0, 1]
The pattern behind it
Design
I reach for it when
- The statement describes a class with methods, not one function.
- Each method needs to be fast, and the structure decides how fast.
Say this before you type. Say each method, the cost you want from it, and the structure that earns that cost.
All 27 Design problemsStack
I reach for it when
- Things must close in the reverse order they opened.
- You need the nearest earlier or later item that is bigger or smaller.
Say this before you type. Say what each item on the stack is waiting for, and what lets you pop it.
All 17 Stack problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Prep guides that list this problem
Our company tags come from public interview write-ups. None of these is a confirmed question.