Coding
Parsing & Data

Command Interpreter

Difficulty

Asked at Squarepoint Capital

Theory: Parsing and Data Hygiene

Read the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.

Small stack machines hide everywhere in trading infrastructure: pricing expression DSLs, strategy config languages, protocol test harnesses. The interview version checks two things at once: can you write a clean dispatch loop, and are you disciplined about error paths. Like an order gateway, the interpreter must stop at the first bad instruction and say exactly where it died.

Implement run_program(lines), taking a list of strings, one command per line, operating on a stack of integers. Tokens are separated by whitespace (line.split()). The commands:

  • PUSH n: push the integer n. Exactly one argument; valid arguments are an optional leading - followed by one or more digits (so -4 and 007 are valid, +5, 1_0 and x are not).
  • POP: discard the top value (needs 1 value on the stack).
  • DUP: push a copy of the top value (needs 1).
  • SWAP: exchange the top two values (needs 2).
  • ADD, SUB, MUL: pop the top value a, then b, and push b + a, b - a, b * a respectively (each needs 2).

Any violation aborts immediately with ("ERROR", line_number) using 1-based line numbers: a blank line, an unknown command, a wrong argument count, a bad PUSH argument, or a stack underflow. Commands are case-sensitive. If every line executes, return ("OK", stack) where stack is a tuple of the remaining values, bottom to top (an empty program returns ("OK", ())).

Examples

run_program(["PUSH 3", "PUSH 4", "ADD", "PUSH 2", "MUL"])
# ('OK', (14,))  (3 + 4) * 2

run_program(["PUSH 5", "DUP", "SUB", "POP", "POP"])
# ('ERROR', 5)  5 - 5 = 0 is popped, then the second POP underflows

Constraints

  • Up to \(2 \times 10^5\) lines; values are Python integers (no overflow concerns).
  • One pass, \(O(1)\) work per command; the hidden volume test just checks you did not do anything accidentally quadratic.
Rate this problem
Language: Pythonrun_program
Sample tests

Run your code to check it against the sample tests. Results appear here.

Rate this problem
Next in Quant Dev 50Execution Log Replay