155. Min Stack 🗃️
Difficulty: Medium
- Tags: Stack
, Design
Problem Statement 📜
Design a stack that supports the following operations in constant time O(1)
:
void push(int val)
: Push the elementval
onto the stack.void pop()
: Remove the element on the top of the stack.int top()
: Retrieve the top element of the stack.int getMin()
: Retrieve the minimum element in the stack.
You must implement all these methods in constant time.
Examples 🌟
🔹 Example 1:
Input:
Output:
Explanation:
Constraints ⚙️
-2^31 <= val <= 2^31 - 1
Methods
pop
,top
, andgetMin
will always be called on non-empty stacks.At most
3 * 10^4
calls will be made topush
,pop
,top
, andgetMin
.
Solution 💡
To achieve O(1)
time complexity for all operations, we can use two stacks:
Primary stack to store all elements.
Min stack to keep track of the minimum value at each level of the stack.
For every push
, we add the value to the primary stack, and update the min stack with the current minimum value. For pop
, we remove from both stacks.
Java Solution
Explanation of the Solution
Two Stacks:
The main stack holds all the elements.
The min stack maintains the current minimum at every point.
Push Operation:
Push the element onto the main stack.
Update the min stack with the smaller of the new element and the current minimum.
Pop Operation:
Remove the top element from both stacks.
Top Operation:
Return the top element of the main stack.
GetMin Operation:
Retrieve the top element of the min stack, which represents the minimum.
Time Complexity ⏳
Push:
O(1)
Pop:
O(1)
Top:
O(1)
GetMin:
O(1)
Space Complexity 💾
O(n): We use two stacks, each storing up to
n
elements.
You can find the full solution here.
Last updated