Constant-Time Minimum Stack
Problem statement
Implement a stack that supports pushing, popping, reading the top value, and retrieving the minimum value, each in O(1) time.
For this exercise, process a finite list of valid operation strings in order, starting with an empty stack:
PUSH x: place integerxon top.POP: remove the top value and produce no output.TOP: append the top value to the result without modifying the stack.MIN: append the smallest value currently in the stack to the result without modifying the stack.
Return the integer results of only TOP and MIN, in operation order. Preserve repeated values as separate stack entries. Every POP, TOP, and MIN is guaranteed to occur while the stack is nonempty. If there are no query operations, return an empty array.
Function
runMinStack(operations: String[]) → int[]Examples
Example 1
operations = ["PUSH -2","PUSH 0","PUSH -3","MIN","POP","TOP","MIN"]return = [-3,0,-2]The first minimum is -3. After popping it, the top is 0 and the minimum among the remaining values is -2.
Example 2
operations = []return = []No operations produce no query results.
Example 3
operations = ["PUSH 5","PUSH 5","MIN","POP","MIN"]return = [5,5]Popping one occurrence of 5 leaves the other occurrence, so both minimum queries return 5.
Constraints
- For this exercise, assume
0 <= operations.length <= 1000. - Every operation is exactly
PUSH x,POP,TOP, orMIN;PUSHuses one space and a base-10 integer without a leading plus sign. -10^9 <= x <= 10^9.- Every non-push operation has a nonempty stack. The whole sequence must run in
O(m)time formoperations, withO(1)work per operation after allocating storage.