Introduction
The Min Stack problem involves designing a stack that supports retrieving the minimum element efficiently.
The stack should support:
push(x)pop()
top()
getMin()
Rules:
- all operations should work efficiently
- minimum element retrieval should be fast
The task is to:
- design a stack supporting
constant-time minimum lookup
This problem is one of the most important applications of:
Stack Data StructureThis problem helps in understanding:
- stack design
- auxiliary stacks
- constant-time retrieval
- data structure optimization
Example
Operations:push(5)
push(2)
push(7)
getMin()
Output: 2
Explanation: Stack: [5,2,7]
Minimum element: 2
Constraints
-2^31 <= val <= 2^31 - 1Operations:
push, pop, top, getMin will always be valid
Approach 1 : Brute Force Traversal
Explanation
The simplest way is:
- Use normal stack
- Traverse stack whenever:
- getMin() is called
This works but minimum retrieval becomes slow.
Steps
- Push elements normally.
- Pop elements normally.
- Traverse stack for minimum.
- Return smallest element.
Dry Run
Push:5
2
7
Stack: [5,2,7]
Traverse stack:
Minimum = 2
Result:
2
Brute Force Code
Complexity Analysis
Time Complexity:push() -> O(1)pop() -> O(1)
top() -> O(1)
getMin()-> O(n)
Explanation:
Minimum requires traversal.
Space Complexity: O(n)
Explanation:
Stack stores elements.
Approach 2 : Two Stack Optimization
Explanation
The optimized solution uses:
Two StacksIdea:
- one stack stores elements
- another stack stores:
- minimum values
Whenever new minimum appears:
- push into min stack
This allows:
O(1)minimum retrieval.
Steps
- Create normal stack.
- Create min stack.
- Push minimum values separately.
- Remove from min stack when needed.
- Return top of min stack for minimum.
Dry Run
Push 5Main Stack:
[5]
Min Stack:
[5]
Push 2
Main Stack:
[5,2]
Min Stack: [5,2]
Push 7
Main Stack:
[5,2,7]
Min Stack:
[5,2]
getMin():
2
Two Stack Code
Complexity Analysis
Time Complexity:
push() -> O(1)
pop() -> O(1)
top() -> O(1)
getMin() -> O(1)
Explanation:
All operations use stack top access.
Space Complexity: O(n)
Explanation:
Additional min stack is used.
Edge Cases