Min Stack
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Stack.
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
Input: ["MinStack","push","push","push","getMin","pop","top","getMin"]\n[[],[-2],[0],[-3],[],[],[],[]]
Output: [null,null,null,null,-3,null,0,-2]
Approach 1
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.⏱ O(1) for push/pop/top. O(N) for getMin.💾 O(N) for the underlying stack.
Approach 2
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.⏱ O(1) for all operations.💾 O(N) to store pairs.
Approach 3
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.
⏱ O(1) for all operations.💾 O(N)
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.Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.