155. Min Stack 🗃️
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Medium
- Tags: Stack
, Design
Design a stack that supports the following operations in constant time O(1)
:
void push(int val)
: Push the element val
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.
🔹 Example 1:
Input:
Output:
Explanation:
-2^31 <= val <= 2^31 - 1
Methods pop
, top
, and getMin
will always be called on non-empty stacks.
At most 3 * 10^4
calls will be made to push
, pop
, top
, and getMin
.
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.
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.
Push: O(1)
Pop: O(1)
Top: O(1)
GetMin: O(1)
O(n): We use two stacks, each storing up to n
elements.
You can find the full solution .