
Problem
Solution
Submissions
Min Stack with O(1) Operations
Certification: Intermediate Level
Accuracy: 100%
Submissions: 1
Points: 10
Write a C++ program to design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack
class with the following operations:
Operations
MinStack()
: initializes the stack object.void push(int val)
: pushes element val onto the stack.void pop()
: removes the element on the top of the stack.int top()
: gets the top element of the stack.int 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,null,0,-2]
- Explanation:
- MinStack minStack = new MinStack();
- minStack.push(-2);
- minStack.push(0);
- minStack.push(-3);
- minStack.getMin(); // return -3
- minStack.pop();
- minStack.top(); // return 0
- minStack.getMin(); // return -2
Example 2
- Input: ["MinStack","push","push","getMin","push","getMin","pop","getMin"] [[],[5],[3],[],[1],[],[],[]]
- Output: [null,null,null,3,null,1,null,3]
- Explanation:
- MinStack minStack = new MinStack();
- minStack.push(5);
- minStack.push(3);
- minStack.getMin(); // return 3
- minStack.push(1);
- minStack.getMin(); // return 1
- minStack.pop();
- minStack.getMin(); // return 3
Constraints
- -2³¹ ≤ val ≤ 2³¹ - 1
- Methods
pop
,top
andgetMin
operations will always be called on non-empty stacks - At most 3 * 10⁴ calls will be made to
push
,pop
,top
, andgetMin
- 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 an auxiliary stack to keep track of the current minimum element
- When pushing an element, push the current minimum to the auxiliary stack as well
- When popping an element, pop from both stacks
- The top of the auxiliary stack will always contain the current minimum
- Be careful about how to update the minimum when elements are popped