Stack Simulator with Constant-Time Minimum Queries
Stacks & QueuesAuto-graded · 17 test casesLast updated
Simulate a sequence of stack commands and answer minimum queries in constant time by tracking the running minimum alongside each element.
You are asked to simulate a special stack of integers that, besides the usual operations, can report its smallest element immediately.
The stack supports four commands:
"push": place the given integer on top of the stack."pop": remove the element on top of the stack."top": report the element currently on top, without removing it."getMin": report the smallest value currently in the stack.
You receive two lists of equal length. operations[i] is the name of the i-th command, and arguments[i] is the list of arguments for that command. For "push", arguments[i] holds exactly one integer, the value to push. For all other commands, arguments[i] is an empty list.
Process the commands in order, starting from an empty stack, and return a list results of the same length as operations:
- For
"push"and"pop",results[i]isNone. - For
"top",results[i]is the value on top of the stack. - For
"getMin",results[i]is the minimum value among all elements currently in the stack.
Duplicate values are allowed. After a pop, the minimum must reflect only the elements still in the stack. Every "pop", "top" and "getMin" is issued on a non-empty stack, so you never need to handle an empty-stack error.
Each command should run in O(1) time.
Constraints
1 <= len(operations) == len(arguments) <= 3 * 10^4- Each operation is one of
"push","pop","top","getMin". - Pushed values fit in a 32-bit signed integer.
pop,topandgetMinare never called on an empty stack.
Examples
Example 1
Input: run_min_stack(['push', 'push', 'push', 'getMin', 'pop', 'top', 'getMin'], [[2], [0], [3], [], [], [], []])
Output: [None, None, None, 0, None, 0, 0]
Example 2
Input: run_min_stack(['push', 'push', 'getMin', 'pop', 'getMin', 'top'], [[-2], [0], [], [], [], []])
Output: [None, None, -2, None, -2, -2]
Example 3
Input: run_min_stack(['push', 'push', 'push', 'getMin', 'pop', 'getMin', 'pop', 'getMin'], [[5], [5], [-1], [], [], [], [], []])
Output: [None, None, None, -1, None, 5, None, 5]
Hints
Hint 1
Think about what the minimum of the stack looks like at the moment each element was pushed. Does that value change while the element is still in the stack?
Hint 2
Keep a second stack of the same height as the first. Each of its entries stores the minimum of everything at or below that position.
Hint 3
When pushing, the new running minimum is min(value, current running minimum), or just the value if the stack is empty. Popping both stacks together restores the previous minimum automatically, and duplicates are handled correctly.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The difficulty is that after a pop, the minimum may change, and rescanning the stack would cost O(n). The fix is to remember, for every position in the stack, what the minimum was at the moment that element was pushed.
We keep two stacks of equal height:
valuesholds the pushed integers.minsholds, at each index, the minimum ofvalues[0..index].
Commands:
- push v: append
vtovalues. Appendvtominsif the stack was empty, otherwisemin(v, mins[-1]). RecordNone. - pop: remove the last entry from both stacks. Record
None. - top: record
values[-1]. - getMin: record
mins[-1].
Why it is correct
The stack is only modified at its top, so the elements below a given position never change while that position exists. Hence the minimum of everything at or below it is fixed when it is pushed and stays valid until it is popped. The last entry of mins therefore always equals the minimum of the current stack. When an element is popped, its mins entry goes with it, and the new last entry is exactly the minimum of the remaining elements. Duplicates cause no issue because each position stores its own running minimum.
Complexity
- Time: O(1) per command, so O(n) for n commands.
- Space: O(n) for the two stacks.
Reference solution
from typing import List, Optional
def run_min_stack(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
values = []
mins = []
result = []
for op, args in zip(operations, arguments):
if op == "push":
value = args[0]
values.append(value)
mins.append(value if not mins else min(value, mins[-1]))
result.append(None)
elif op == "pop":
values.pop()
mins.pop()
result.append(None)
elif op == "top":
result.append(values[-1])
elif op == "getMin":
result.append(mins[-1])
return result