Stack With O(1) Access to Its Current Minimum
Implement stackOpsMin
Design a stack that supports the usual
push, pop, and top, plus a getMin operation that returns the smallest element currently on the stack — and make every one of those four operations run in O(1) time.
The trick is to never actually compute the minimum on demand. A second, parallel stack tracks it incrementally: every time a value is pushed, the min-stack also gets a push — either the new value itself (if it's smaller than or equal to the current minimum) or a repeat of the current minimum (if the new value is bigger and doesn't change anything). Every pop removes from both stacks together, so the min-stack's top is automatically correct for whatever remains. getMin then becomes nothing more than reading the min-stack's top — the minimum was already known the instant it was needed, because it was maintained the whole time, not searched for.
Example 1:
Input: ops = ["push","push","push","getMin","pop","top","getMin"], args = [5,2,7,0,0,0,0]
Output: [2,7,2,2]
Example 2:
Input: ops = ["push","push","getMin","push","getMin","pop","getMin"], args = [3,3,0,1,0,0,0]
Output: [3,1,1,3]
Example 3:
Input: ops = ["push","pop","getMin","push","push","getMin","pop","getMin"], args = [9,0,0,4,2,0,0,0]
Output: [9,-1,2,2,4]
+ 2 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ ops.length ≤ 20 - ●
ops[i] is one of "push", "pop", "top", "getMin"; args[i] is the value to push (0 for every other operation, unused) - ●
"pop", "top", and "getMin" on an empty stack each return -1
ops =
["push", "push", "push", "getMin", "pop", "top", "getMin"]
args =
[5, 2, 7, 0, 0, 0, 0]