Problem description
Design a stack that supports pushing and popping elements while also being able to report the smallest element it currently holds, with every operation running in constant time.
Implement the MinStack class with the following methods: push(val) adds val to the top of the stack, pop() removes the element on top, top() returns the element on top without removing it, and getMin() returns the minimum element currently in the stack.
Every method must run in O(1) time. The methods top(), pop(), and getMin() will only be called when the stack is non-empty.
Example 1
Input: ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]]
Output: [null,null,null,null,-3,null,0,-2]
After pushing -2, 0, -3, getMin() returns -3. Popping removes -3; top() then returns 0 and getMin() returns -2.
Example 2
Input: ["MinStack","push","push","getMin","pop","getMin"] [[],[5],[3],[],[],[]]
Output: [null,null,null,3,null,5]
With 5 and 3 on the stack, getMin() is 3. After popping 3, the minimum is back to 5.
Constraints
-2^31 <= val <= 2^31 - 1Methods pop, top, and getMin are always called on a non-empty stackAt most 3 * 10^4 calls will be made to push, pop, top, and getMin
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free