Run a Stack Language Interpreter
Problem statement
Execute a simple stack program from instruction index 0 with an empty stack. Return the sequence of strings produced by PRINT, in execution order.
PUSH valuepushes the entire string after the first space, including an empty string.POPremoves the top string; it does nothing on an empty stack.PRINTappends the top string to the output without removing it; on an empty stack it appends"".TRUNCATE kremoves up tokcharacters from the right end of the top string. It leaves an empty string whenkis at least its length, and does nothing on an empty stack.JUMP targetcontinues at the zero-based indextarget.JUMP_IF_EMPTY targetjumps when the stack is empty or its top string is empty; otherwise execution advances normally.
Every instruction other than a taken jump advances to the next index. Reaching index instructions.length ends execution. Inputs are valid and guaranteed to terminate; detecting infinite loops is unnecessary.
Function
runInterpreter(instructions: String[]) → String[]Examples
Example 1
instructions = ["PUSH hello","PRINT","TRUNCATE 2","PRINT"]return = ["hello","hel"]Printing preserves the top value. Truncation then removes its last two characters.
Example 2
instructions = ["PUSH ","JUMP_IF_EMPTY 4","PUSH skip","PRINT","PUSH ok","PRINT"]return = ["ok"]The empty top value takes the jump directly to index 4, skipping the intervening instructions.
Example 3
instructions = ["POP","PRINT","PUSH abc","JUMP 5","PRINT"]return = [""]Popping an empty stack is harmless. The first print emits an empty string, and the final jump exits the program.
Constraints
- For this exercise, assume
0 <= instructions.length <= 1000and at most10000executed instructions. - A pushed value has at most
50printable ASCII characters, excluding line breaks. Its spaces are significant. - Non-
PUSHoperands are unsigned decimal integers. Truncation counts are at most50; jump targets are in[0, instructions.length]. - Opcodes are exactly the uppercase names above. Operand instructions have one separating space;
PUSHrepresents an empty value.POPandPRINThave no operand.