Simulate a stack driven by a stream of text commands and report what it outputs. The commands arrive as one string of whitespace-separated tokens:
-
U num
: push the integer
num
onto the stack.
-
O
: pop the top value off the stack and output it.
-
X
: the input stream has ended.
Return the output values in the order they were popped.
Function Signature
def simulate_stack(commands: str) -> list[int]:
Rules
-
Tokens are separated by one or more whitespace characters (spaces or newlines).
-
U
is always followed by exactly one integer token, written in decimal with an optional leading
-
.
-
Each
O
removes the current top value and appends it to the output.
-
X
appears exactly once, as the last token. Values still on the stack when
X
is reached are not output.
-
The original prompt printed the popped values separated by spaces, so the printed output
-3 3
corresponds to the return value
[-3, 3]
.
Constraints
-
The input has between 1 and 200,000 tokens.
-
-10^9 <= num <= 10^9
-
Every
O
is issued while the stack is non-empty.
Examples
Example 1
Input: commands = "U 3 U -3 O O X"
Output: [-3, 3]
3 is pushed, then -3. The first O pops -3 and the second pops 3.
Example 2
Input: commands = "U 5 U 7 O U 2 X"
Output: [7]
Only one pop happens. 5 and 2 are still on the stack at X, so they are not output.
Example 3
Input: commands = "X"
Output: []
The stream ends before any command runs.