
Problem
Solution
Submissions
Min Stack
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class with the following operations: - MinStack() initializes the stack object - void push(int val) pushes the 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:
Step 1: MinStack minStack = new MinStack();
Step 2: minStack.push(-2);
Step 3: minStack.push(0);
Step 4: minStack.push(-3);
Step 5: minStack.getMin() returns -3 (minimum element in stack)
Step 6: minStack.pop() removes the top element (-3)
Step 7: minStack.top() returns 0 (current top element)
Step 8: minStack.getMin() returns -2 (current minimum element)
Example 2
- Input: ["MinStack", "push", "push", "getMin", "push", "getMin", "pop", "getMin"] [[], [5], [7], [], [2], [], [], []]
- Output: [null, null, null, 5, null, 2, null, 5]
- Explanation:
Step 1: MinStack minStack = new MinStack();
Step 2: minStack.push(5);
Step 3: minStack.push(7);
Step 4: minStack.getMin() returns 5 (minimum element in stack)
Step 5: minStack.push(2);
Step 6: minStack.getMin() returns 2 (new minimum element)
Step 7: minStack.pop() removes the top element (2)
Step 8: minStack.getMin() returns 5 (minimum element after pop)
Constraints
- -2^31 <= val <= 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) where n is the number of elements in the stack
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 storing all elements and another for tracking minimum values
- When pushing a new element, compare it with the current minimum
- If the new element is smaller or equal to the current minimum, push it onto the minimum stack as well
- When popping an element, check if it equals the current minimum
- If the popped element equals the current minimum, also pop from the minimum stack