KatInterview

Run a Tiny Postfix Command Interpreter with Error Codes

Stacks & QueuesModel answer
EasyModel answerStacks & Queuesstacksimulationparsing

Last updated

Simulate a small stack machine over whitespace-separated tokens, handling arithmetic, DUP, POP and PRINT, and stop at the first error while keeping the output produced so far.

Task

Write an interpreter for a minimal stack-based language over integers. The program arrives as one string of tokens separated by whitespace, and you run it from the first token to the last.

The interpreter keeps two things: a stack of integers and a list of printed values.

Tokens

  • Integer literal: an optional + or - followed by one or more ASCII digits, such as 42, -7 or +0. Push its value.
  • +, -, *, /: pop b first, then pop a, and push the result of a op b. For /, the result is the quotient truncated toward zero, so -7 / 2 gives -3.
  • DUP: push a copy of the top value.
  • POP: remove the top value and discard it.
  • PRINT: pop the top value and append it to the output list.

Commands are case-sensitive. A lone + or - is an operator, not a number.

Errors

Execution stops at the first error. Everything already appended to the output stays in the result. Possible error codes:

  • "UNDERFLOW": the operation needs more values than the stack holds. For binary operators, this check comes before the zero-divisor check.
  • "ZERODIVISION": / is executed with a divisor of 0.
  • "INVALID_TOKEN": the token is neither a known command nor a valid integer literal.

Signature

def evaluate_stack_program(program: str) -> tuple[list[int], str | None]:
    """Return (output_list, error_code); error_code is None on success."""

Examples

evaluate_stack_program("10 4 - PRINT")          # ([6], None)
evaluate_stack_program("7 PRINT 5 0 / PRINT")   # ([7], "ZERODIVISION")
evaluate_stack_program("3 DUP * PRINT POP")     # ([9], "UNDERFLOW")

Constraints

  • 0 <= len(program) <= 10^4
  • Tokens are separated by one or more whitespace characters. An empty or whitespace-only program returns ([], None).
  • All values fit in a signed 64-bit integer.
  • Values left on the stack when the program ends are not an error.

What to explain

Describe your approach, how you classify tokens, how you handle the division rule and error order, the time and space complexity, and the edge cases you would test.

Hints

Hint 1

Split on whitespace and process tokens in order. Decide what each token is before touching the stack: first check the fixed command names, then check whether it is a well-formed literal, otherwise report an invalid token.

Hint 2

For binary operators, the first value popped is the right-hand operand. Verify that at least two values are on the stack before popping, and only then test for a zero divisor.

Hint 3

Language-level shortcuts can disagree with the spec. Floor division rounds the wrong way for negatives, and a permissive int() conversion accepts things like underscores or non-ASCII digits. Use an exact truncating division on absolute values and an explicit ASCII pattern like [+-]?[0-9]+ for literals.