FastPrepRun a Stack Language Interpreter

Run a Stack Language Interpreter

Jane Street logoJane Street● MediumFULLTIMEPHONE SCREEN
Learn

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 value pushes the entire string after the first space, including an empty string.
  • POP removes the top string; it does nothing on an empty stack.
  • PRINT appends the top string to the output without removing it; on an empty stack it appends "".
  • TRUNCATE k removes up to k characters from the right end of the top string. It leaves an empty string when k is at least its length, and does nothing on an empty stack.
  • JUMP target continues at the zero-based index target.
  • JUMP_IF_EMPTY target jumps 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 <= 1000 and at most 10000 executed instructions.
  • A pushed value has at most 50 printable ASCII characters, excluding line breaks. Its spaces are significant.
  • Non-PUSH operands are unsigned decimal integers. Truncation counts are at most 50; jump targets are in [0, instructions.length].
  • Opcodes are exactly the uppercase names above. Operand instructions have one separating space; PUSH represents an empty value. POP and PRINT have no operand.

More Jane Street problems

See Jane Street hiring insights
public String[] runInterpreter(String[] instructions) {
    // Write your code here.
}
instructions["PUSH hello","PRINT","TRUNCATE 2","PRINT"]
expected["hello", "hel"]
Checking account…