
Problem
Solution
Submissions
Stack with Min Operation
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time (O(1)). The stack should support the following operations:
- Push(int x): Pushes element x onto the stack.
- Pop(): Removes the element on top of the stack and returns it.
- Top(): Returns the element on top of the stack without removing it.
- GetMin(): Retrieves the minimum element in the stack.
Example 1
- Input:
["MinStack", "push", "push", "push", "getMin", "pop", "top", "getMin"]
[[], [-2], [0], [-3], [], [], [], []] - Output:
[null, null, null, null, -3, -3, 0, -2] - Explanation:
- MinStack minStack = new MinStack();
- minStack.push(-2);
- minStack.push(0);
- minStack.push(-3);
- minStack.getMin(); // return -3
- minStack.pop(); // removes -3
- minStack.top(); // return 0
- minStack.getMin(); // return -2
Example 2
- Input:
["MinStack", "push", "push", "getMin", "push", "getMin", "pop", "getMin"]
[[], [5], [7], [], [1], [], [], []] - Output:
[null, null, null, 5, null, 1, 1, 5] - Explanation:
- MinStack minStack = new MinStack();
- minStack.push(5);
- minStack.push(7);
- minStack.getMin(); // return 5
- minStack.push(1);
- minStack.getMin(); // return 1
- minStack.pop(); // removes 1
- minStack.getMin(); // return 5
Constraints
- -2^31 ≤ x ≤ 2^31 - 1
- Methods pop, top and getMin operations will always be called on non-empty stacks
- At most 3 * 10^4 calls will be made to push, pop, top, and getMin
- Time Complexity: O(1) for all operations
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use two stacks: one for the actual values and one for minimum values
- Update the minimum stack carefully during push and pop operations
- Consider edge cases like multiple instances of the minimum value
- Optimize space usage by only adding to the minimum stack when necessary
- Consider using a single stack with pairs of (value, current_min)