stack
design
Simulate a stack that supports retrieving the current minimum in constant time.
You are given two parallel arrays operations and values. At index i:
- if
operations[i] == "push", pushvalues[i]onto the stack; - if
operations[i] == "pop", remove the current top element; - if
operations[i] == "top", append the current top element to the answer; - if
operations[i] == "getMin", append the current minimum element to the answer.
values[i] is ignored for pop, top, and getMin operations. The input is always valid: every queried or popped stack is non-empty.
Input / output
- Input:
operations: string[],values: int[] - Output:
int[]containing everytopandgetMinresult in order
Examples
operations = ["push","push","push","getMin","pop","top","getMin"],values = [-2,0,-3,0,0,0,0]returns[-3,0,-2]. The minimum drops to-3, then returns to-2after that value is popped.operations = ["push","push","getMin","push","top"],values = [5,1,0,1,0]returns[1,1]. The duplicated minimum should still be tracked correctly.operations = ["push","top","getMin"],values = [7,0,0]returns[7,7]. A one-element stack has the same top and minimum.
Constraints
1 <= operations.length == values.length <= 3 * 10^4operations[i]is one of"push","pop","top","getMin"-10^5 <= values[i] <= 10^5- All
pop,top, andgetMinoperations are valid
Edge cases
- The minimum can appear multiple times.
- Negative numbers are allowed.
- The stack can shrink back to one element after many operations.
Target complexity
- Aim for
O(1)time per operation. - Aim for
O(n)additional space in the worst case.
Hints
- A plain stack gives
push,pop, andtop, but not the current minimum fast enough. - Store a second stack where each position remembers the minimum value seen up to that depth.
Follow-up
How would you redesign this if the stack also needed getMax() in constant time?
Examples
Example 1
Input: operations = ["push","push","push","getMin","pop","top","getMin"], values = [-2,0,-3,0,0,0,0]
Output: [-3,0,-2]
Example 2
Input: operations = ["push","push","getMin","push","top"], values = [5,1,0,1,0]
Output: [1,1]
Example 3
Input: operations = ["push","top","getMin"], values = [7,0,0]
Output: [7,7]
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.