The Constant Min Stack
MediumAcc. 88.2%
+35 XP 15
Instant Intelligence (O(1))
Retrieving the minimum value from a stack usually requires looking at every element ($O(n)$). However, by using a Dual Stack strategy, we can know the minimum value instantly ($O(1)$) no matter how large the stack grows!
The Assignment
Your mission is to build a high-performance Min-Stack.
- Maintain two internal arrays: a Data Stack and a Min-Tracking Stack.
- When pushing a value
x:- Push
xto the Data Stack. - Push the current minimum (either
xor the top of the Min-Tracking Stack) to the Min-Tracking Stack.
- Push
- Handle these commands:
- "PUSH": Add the value to both trackers.
- "POP": Remove the top from both and print the value.
- "GETMIN": Print the top value of the Min-Tracking Stack.
01EXAMPLE 1
Input
["PUSH", "PUSH", "GETMIN"], [-2, 0, 0]Output
-2Explanation: Current stack [-2, 0], min is -2.
Constraints
- All operations MUST be O(1) time.
Data StructuresStack
JavaScriptSystem handles I/O — write your function only
Loading...
1 Hidden
Input Arguments
commands["PUSH","PUSH","GETMIN"]
values[-2,-5,0]
Expected Output
-5
Click RUN to test your solution