Practice Problem
Min Stack
Difficulty: Medium
Design a stack that supports push, pop, top, and retrieving the minimum element, all in constant time.
Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack(): Initializes the stack object.push(val): Pushes the elementvalonto the stack.pop(): Removes the element on the top of the stack.top(): Gets the top element of the stack.getMin(): Retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.
Examples
Example 1:
Input:
MinStack(), push(-2), push(0), push(-3), getMin(), pop(), top(), getMin()
Output:
null, null, null, null, -3, null, 0, -2
Explanation:
MinStack minStack = new MinStack();
minStack.push(-2); // stack: [-2]
minStack.push(0); // stack: [-2, 0]
minStack.push(-3); // stack: [-2, 0, -3]
minStack.getMin(); // return -3
minStack.pop(); // stack: [-2, 0]
minStack.top(); // return 0
minStack.getMin(); // return -2Constraints
-2^31 <= val <= 2^31 - 1- Methods
pop,top, andgetMinwill always be called on non-empty stacks. - At most
3 * 10^4calls will be made topush,pop,top, andgetMin.
Expected Complexity
- Time: O(1) per operation
- Space: O(n)
MEDIUM
Stack
Data Structures
Intermediate
0 views
Solution
Hints
Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium
This section is available for CodeSnatch Premium members only.
