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.

Available in Python and C++. You are solving it in C++. Switch to Python

Implement run_program(lines), a small stack machine. It takes a sequence of strings, one command per line, and runs them on a stack of integers. It stops at the first bad instruction and reports which line it was. Pricing expression languages, config languages and protocol test harnesses use the same shape.

Tokens are separated by whitespace. 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 an error result carrying the line number, counted from 1: 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 a success result carrying the remaining stack values, bottom to top.

std::pair<std::string, std::vector<long long>> run_program(
    const std::vector<std::string>& lines);

The first element is "OK" or "ERROR". On success the second is the stack, bottom to top (empty for an empty program); on an error it holds exactly one value, the 1-based line number, so {"ERROR", {5}} is an error on line 5. Values are long long; the tests stay inside it.

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^6\) lines; values fit in a long long (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:
Python 3.12C++23
run_program
Rate this problem