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 elementvalonto 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:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]Output:
Explanation:
Constraints โ๏ธ
-2^31 <= val <= 2^31 - 1Methods
pop,top, andgetMinwill always be called on non-empty stacks.At most
3 * 10^4calls 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
nelements.
You can find the full solution here.
Last updated
Was this helpful?