FastPrepStack Command Output
Problem · Stack

Stack Command Output

Learn this problem
EasyWex logoWexFULLTIMEPHONE SCREEN

Problem statement

Process a command string commands using an initially empty stack. Return the values removed by pop commands, in the order they are removed.

  • U value pushes the signed integer value onto the stack.
  • O removes the top value and appends it to the output.
  • X ends the command string. Values still on the stack are not output.

For this exercise, assume the input is valid: tokens are separated by one or more spaces, tabs, or newlines, optional whitespace may surround the string, exactly one X is the final token, and every O has a value available to pop. Integers use ordinary decimal notation with an optional leading minus sign.

Function

stackOutput(commands: String) → int[]

Examples

Example 1

commands = "U 3 U -3 O O X"return = [-3,3]

Push 3, then -3. The first pop removes -3; the second removes 3.

Example 2

commands = "U 8 O U 4 U 9 O X"return = [8,9]

The pops remove 8 and then 9. The remaining 4 is not output when X ends processing.

Constraints

  • 1 <= commands.length <= 10^5.
  • There are at most 10^4 commands, including X.
  • Every pushed value is between -10^9 and 10^9, inclusive.
  • The command sequence satisfies the validity rules in the statement.

More Wex problems

drafts saved locally
public int[] stackOutput(String commands) {
    // Write your code here.
}
commands"U 3 U -3 O O X"
expected[-3,3]
checking account