Min Stack
Master this topic with zero to advance depth.
Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Visual Representation
Push: -2, 0, -3
Stack: MinStack:
| -3 | | -3 |
| 0 | | -2 |
| -2 | | -2 |
+----+ +----+
getMin() -> -3
pop()
top() -> 0
getMin() -> -2Examples
Level I: Single Stack (Brute Force Min)
Intuition
Use a standard stack for push, pop, and top. For getMin(), iterate over the entire stack to find the minimum value. This saves space over a two-stack approach but sacrifices the constant-time operation for querying the minimum.
Level II: Single Stack (Value-Min Pairs)
Intuition
Instead of two separate stacks, we can store pairs on a single stack. Each entry on the stack will be (current_value, current_min_so_far). This is conceptually simpler and ensures the value and its corresponding minimum are always synchronized.
Level III: Optimal (Two Stacks)
Intuition
Maintain two stacks: one for all elements and another to keep track of the minimum at each state. When pushing a value, if it is less than or equal to the current minimum, push it onto the min stack as well. This ensures O(1) retrieval.
Detailed Dry Run
| Operation | Value | Stack | MinStack | Output |
|---|---|---|---|---|
| push | -2 | [-2] | [-2] | - |
| push | 0 | [-2, 0] | [-2] | - |
| push | -3 | [-2, 0, -3] | [-2, -3] | - |
| getMin | - | - | - | -3 |
| pop | - | [-2, 0] | [-2] | - |
⚠️ Common Pitfalls & Tips
In Java, use .equals() instead of == for Stack comparisons as Integer objects might be outside the cache range.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.