Stack-Based Postfix Integer Interpreter

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement evaluate_stack_program(program: str) -> Tuple[List[int], Optional[str]], an interpreter for a small postfix integer language. A program string contains zero or more whitespace-delimited tokens evaluated strictly from left to right against an initially empty integer LIFO stack and an initially empty output list.

Each token obeys one of the following rules:

  • Signed or unsigned integer literal: an optional single sign character (+ or -) immediately followed by one or more ASCII digits 0-9 (such as 18, -12, +0, or 005). Pushes its integer value onto the stack.
  • Binary arithmetic (+, -, *, /): requires at least two integers on the stack; pops the top element as the right-hand operand b, pops the next element as the left-hand operand a, and pushes a + b, a - b, a * b, or the integer quotient of a / b truncated toward zero (for example, 9 / -2 evaluates to -4 and -9 / 4 evaluates to -2).
  • DUP: requires at least one integer on the stack; pushes a second copy of the current top integer.
  • POP: requires at least one integer on the stack; removes and discards the current top integer.
  • PRINT: requires at least one integer on the stack; pops the current top integer and appends it to the output list.

If every token executes without error, return (output_list, None) — values remaining on the stack at the end of the token stream are valid and ignored. If a token fails, stop immediately without processing any subsequent tokens, keep every integer already appended to output_list, and return (output_list, error_code) using one of three exact strings:

  • "UNDERFLOW": the stack holds fewer elements than the command or operator requires (checked before inspecting operand values, so "0 /" reports "UNDERFLOW").
  • "ZERODIVISION": "/" has two operands on the stack and the popped right-hand divisor b equals 0.
  • "INVALID_TOKEN": the token matches neither a supported command/operator nor a valid integer literal.

Examples

Example 1

program = "15 6 - -2 / PRINT"
# Output: ([-4], None)

Walk-through: "15" and "6" push onto the stack ([15, 6]). "-" pops b = 6 then a = 15 and pushes 15 - 6 = 9. "-2" pushes -2 ([9, -2]). "/" pops b = -2 then a = 9 and pushes 9 / -2 truncated toward zero (-4). "PRINT" pops -4 into the output list, finishing cleanly with ([-4], None).

Example 2

program = "+12 PRINT 8 4 4 - / 99 PRINT"
# Output: ([12], "ZERODIVISION")

Walk-through: "+12" pushes 12 and "PRINT" emits 12 (output = [12]). Next, "8", "4", "4" produce [8, 4, 4], and "-" replaces the top two 4s with 0 ([8, 0]). "/" pops b = 0 and a = 8, halts immediately with "ZERODIVISION", and preserves [12] while skipping 99 PRINT.

Example 3

program = "5 DUP * 20 + PRINT POP"
# Output: ([45], "UNDERFLOW")

Walk-through: "5" followed by "DUP" and "*" computes 25; "20" and "+" compute 45; "PRINT" pops 45 into output = [45], leaving the stack empty. The trailing "POP" then fails on the empty stack and returns ([45], "UNDERFLOW").

Constraints

  • 0 <= len(program) <= 10^4
  • Tokens are separated by arbitrary runs of spaces, tabs, or newlines; an empty or whitespace-only string returns ([], None).
  • Command names (DUP, POP, PRINT) are case-sensitive, and integer literals allow only ASCII digits 0-9 after at most one leading + or -.
  • Every pushed literal and intermediate arithmetic result fits within a signed 64-bit integer (-2^63 to 2^63 - 1).

Step-by-step walkthrough

  1. Understand how a stack interpreter executes tokens

    A stack-based language (also called postfix or Reverse Polish Notation) evaluates expressions left to right without parentheses by storing intermediate numbers on a LIFO (Last-In, First-Out) stack — like a pile of trays where you always push onto the top and pop from the top:

    Program: "15  6  -  -2  /  PRINT"
    
    Token "15", "6"   Token "-"                  Token "-2", "/"              Token "PRINT"
                      pop b = 6, pop a = 15      pop b = -2, pop a = 9
    +----+            compute a - b = 9          compute 9 / -2 -> -4
    |  6 | <- top     +----+                     +----+
    | 15 |            |  9 | <- top              | -4 | <- top                (empty stack)
    +----+            +----+                     +----+                       output = [-4]
    

    Every token falls into one of these exact rules:

    Token Stack items needed Action
    Integer literal (18, -12, +0) 0 Push the integer onto stack
    +, -, *, / 2 Pop right operand b, pop left operand a, push a op b (/ truncates toward 0)
    DUP 1 Push a copy of stack[-1]
    POP 1 Remove and discard stack[-1]
    PRINT 1 Pop stack[-1] and append it to output

    Before writing code, pin down four boundary rules implied by the specification:

    • Stop on the first error and preserve earlier output: Returning (output, error_code) right away leaves every previously printed integer intact.
    • Check UNDERFLOW before ZERODIVISION: On "0 /", only one integer sits on the stack, so execution fails with "UNDERFLOW" before / inspects a divisor.
    • Leftover numbers on the stack are valid: "1 2 3" completes cleanly with ([], None).
    • program.split() handles all whitespace: Calling .split() with no arguments splits on any run of spaces, tabs, or newlines and returns [] on "" or " \n\t".
  2. Parse signed integer literals without accepting Python quirks

    Notice a subtle lexical distinction: bare "+" and "-" are binary operators, whereas "+12" and "-2" are integer literals. Dispatching exact command/operator strings first (or requiring at least one ASCII digit after an optional sign) keeps them cleanly separated.

    Why not validate literals with try: int(token)? Because Python's built-in int() accepts syntax outside our language grammar:

    int("1_000")  -> 1000   (Python allows underscore separators; our grammar forbids them!)
    int("٣")      -> 3      (Python accepts non-ASCII Unicode digits; we want strict '0'-'9')
    

    Writing an explicit character check for at most one leading "+" or "-" followed by one or more ASCII digits "0123456789" enforces the exact grammar, after which int(token) converts "18", "-12", "+0", or "005" safely.

    DIGITS = "0123456789"
    
    
    def is_integer_literal(token: str) -> bool:
        """Return True iff token is an optional '+'/'-' followed by >= 1 ASCII digits."""
        if not token:
            return False
        # Strip a single optional leading sign; bare "+" or "-" leaves body == "" (False).
        body = token
        if body[0] == "+" or body[0] == "-":
            body = body[1:]
        if body == "":
            return False
        # Check ASCII digits explicitly instead of int(token), which would accept "1_000".
        for ch in body:
            if ch not in DIGITS:
                return False
        return True
    
  3. Handle operand order and exact truncation toward zero

    Two arithmetic traps catch many submissions:

    1. Operand order (b pops first, a pops second): In "15 6 -", 15 is pushed first and 6 sits on top. The first stack.pop() returns b = 6, and the second returns a = 15, giving a - b = 9 (not -9).
    2. Division truncated toward zero on 64-bit integers:
      • Python's // performs floor division (rounding toward -infinity), which disagrees with truncation toward 0 whenever one operand is negative and there is a non-zero remainder: text Exact quotient: -9 / 4 = -2.25 Truncate toward 0: -2 (drop the .25 fraction) Floor division //: -3 (round down toward -infinity — WRONG!)
      • Meanwhile, writing int(a / b) converts a and b to 64-bit IEEE-754 floats, which only carry 53 bits of precision (2^53 = 9,007,199,254,740,992). On larger 64-bit signed integers, float division silently corrupts the low bits: text int(9007199254740993 / 1) -> 9007199254740992 (off by 1!) int(9223372036854775807 / 3) -> 3074457345618258432 (exact: 3074457345618258602)

    To stay 100% exact across all 64-bit integers, compute abs(a) // abs(b) on non-negative magnitudes (where floor division and truncation toward zero agree!) and negate the result when a and b have opposite signs:

    def divide_toward_zero(a: int, b: int) -> int:
        """Compute integer quotient a / b truncated toward zero, exact for 64-bit ints."""
        quotient = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            return -quotient
        return quotient
    
    
    def apply_binary(op: str, a: int, b: int) -> int:
        """Apply '+', '-', '*', or '/' to left operand a and right operand b."""
        if op == "+":
            return a + b
        if op == "-":
            return a - b
        if op == "*":
            return a * b
        return divide_toward_zero(a, b)
    
  4. Execute left to right and stop on the first error

    Now the main loop is clean and direct: iterate over program.split(), verify stack depth before popping any operands, and return output, "<ERROR>" as soon as a rule fails.

    from typing import List, Optional, Tuple
    
    BINARY_OPERATORS = ("+", "-", "*", "/")
    
    
    def evaluate_stack_program(program: str) -> Tuple[List[int], Optional[str]]:
        """Execute whitespace-separated tokens; return (outputs_so_far, error_or_None)."""
        stack: List[int] = []
        output: List[int] = []
    
        for token in program.split():
            if token in BINARY_OPERATORS:
                if len(stack) < 2:
                    return output, "UNDERFLOW"
                b = stack.pop()
                a = stack.pop()
                if token == "/" and b == 0:
                    return output, "ZERODIVISION"
                stack.append(apply_binary(token, a, b))
            elif token == "DUP":
                if not stack:
                    return output, "UNDERFLOW"
                stack.append(stack[-1])
            elif token == "POP":
                if not stack:
                    return output, "UNDERFLOW"
                stack.pop()
            elif token == "PRINT":
                if not stack:
                    return output, "UNDERFLOW"
                output.append(stack.pop())
            elif is_integer_literal(token):
                stack.append(int(token))
            else:
                return output, "INVALID_TOKEN"
    
        return output, None
    
  5. Trace two sample programs step by step

    First, trace Example 3 ("5 DUP * 20 + PRINT POP"):

    Token    Stack before   Action                                Stack after   output
    -------  -------------  ------------------------------------  ------------  ------
    "5"      []             push literal 5                        [5]           []
    "DUP"    [5]            copy top (5)                          [5, 5]        []
    "*"      [5, 5]         pop b=5, pop a=5, push 5 * 5 = 25     [25]          []
    "20"     [25]           push literal 20                       [25, 20]      []
    "+"      [25, 20]       pop b=20, pop a=25, push 45           [45]          []
    "PRINT"  [45]           pop 45, append to output              []            [45]
    "POP"    []             need 1 item, have 0 -> halt!          --            [45]
    
    Returned: ([45], "UNDERFLOW")
    

    Second, trace Example 2 ("+12 PRINT 8 4 4 - / 99 PRINT") to verify zero-division halting and partial output preservation:

    Token    Stack before   Action                                Stack after   output
    -------  -------------  ------------------------------------  ------------  ------
    "+12"    []             push literal 12                       [12]          []
    "PRINT"  [12]           pop 12, append to output              []            [12]
    "8"      []             push literal 8                        [8]           [12]
    "4"      [8]            push literal 4                        [8, 4]        [12]
    "4"      [8, 4]         push literal 4                        [8, 4, 4]     [12]
    "-"      [8, 4, 4]      pop b=4, pop a=4, push 4 - 4 = 0      [8, 0]        [12]
    "/"      [8, 0]         pop b=0, pop a=8 -> b == 0, halt!     --            [12]
    "99"...  --             never executed                        --            [12]
    
    Returned: ([12], "ZERODIVISION")
    
  6. Put the complete solution together

    Here is the complete interpreter ready to run against all test cases.

    from typing import List, Optional, Tuple
    
    DIGITS = "0123456789"
    BINARY_OPERATORS = ("+", "-", "*", "/")
    
    
    def is_integer_literal(token: str) -> bool:
        """Return True iff token is an optional '+'/'-' followed by >= 1 ASCII digits."""
        if not token:
            return False
        # Strip a single optional leading sign; bare "+" or "-" leaves body == "" (False).
        body = token
        if body[0] == "+" or body[0] == "-":
            body = body[1:]
        if body == "":
            return False
        # Check ASCII digits explicitly instead of int(token), which would accept "1_000".
        for ch in body:
            if ch not in DIGITS:
                return False
        return True
    
    
    def divide_toward_zero(a: int, b: int) -> int:
        """Compute integer quotient a / b truncated toward zero, exact for 64-bit ints."""
        # Python's // floors toward -infinity (-9 // 4 == -3), and float int(a / b) loses
        # precision above 2^53. Integer // on absolute values stays exact at every size.
        quotient = abs(a) // abs(b)
        if (a < 0) != (b < 0):
            return -quotient
        return quotient
    
    
    def apply_binary(op: str, a: int, b: int) -> int:
        """Apply '+', '-', '*', or '/' to left operand a and right operand b."""
        if op == "+":
            return a + b
        if op == "-":
            return a - b
        if op == "*":
            return a * b
        return divide_toward_zero(a, b)
    
    
    def evaluate_stack_program(program: str) -> Tuple[List[int], Optional[str]]:
        """Execute whitespace-separated tokens; return (outputs_so_far, error_or_None)."""
        # stack: LIFO list of ints, e.g. [15, 6] where stack[-1] (6) is the top element
        stack: List[int] = []
        # output: ints emitted by PRINT before termination, e.g. [-4]
        output: List[int] = []
    
        # Phase 1 — Split on any run of spaces/tabs/newlines (empty input -> [] tokens).
        for token in program.split():
            # Phase 2 — Dispatch operators/commands first, then signed integer literals.
            if token in BINARY_OPERATORS:
                # Check operand count BEFORE division-by-zero so "0 /" reports UNDERFLOW.
                if len(stack) < 2:
                    return output, "UNDERFLOW"
                # First pop is the top/right operand b; second pop is the left operand a.
                b = stack.pop()
                a = stack.pop()
                if token == "/" and b == 0:
                    return output, "ZERODIVISION"
                stack.append(apply_binary(token, a, b))
            elif token == "DUP":
                if not stack:
                    return output, "UNDERFLOW"
                stack.append(stack[-1])
            elif token == "POP":
                if not stack:
                    return output, "UNDERFLOW"
                stack.pop()
            elif token == "PRINT":
                if not stack:
                    return output, "UNDERFLOW"
                output.append(stack.pop())
            elif is_integer_literal(token):
                stack.append(int(token))
            else:
                return output, "INVALID_TOKEN"
    
        return output, None
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a spring-loaded stack of cafeteria trays with numbers written on them — a LIFO (Last-In, First-Out) stack, meaning the last tray placed on top is always the first tray lifted back off. Scanning the program from left to right, each integer literal sets a new numbered tray on top of the stack, while each command lifts the top one or two trays, computes the result, and places the answer tray back on top.

Three subtle traps break quick-and-dirty solutions: calling Python's int(token) to detect numbers wrongly accepts underscored tokens like "1_000"; using Python's // operator floors -9 // 4 down to -3 instead of truncating toward zero (-2); and writing int(a / b) casts 64-bit integers to floating-point numbers, which hold only 53 bits of precision and silently corrupt integers above 2^53 (such as 9007199254740993). Checking ASCII digits explicitly and dividing non-negative magnitudes via integer arithmetic (abs(a) // abs(b)) eliminates all three bugs.

Walk through "15 6 - -2 / PRINT" step by step: 1. "15" pushes 15 -> stack = [15]. 2. "6" pushes 6 -> stack = [15, 6] (6 sits on top). 3. "-" pops the top item as right operand b = 6, pops the next item as left operand a = 15, and pushes a - b = 9 -> stack = [9]. 4. "-2" pushes -2 -> stack = [9, -2], and "/" pops b = -2, pops a = 9, and pushes 9 / -2 truncated toward zero (-4) -> stack = [-4]. 5. "PRINT" pops -4 into output = [-4], finishing with ([-4], None).

Complexity

  • Time: O(n), where n is the length of program in characters. program.split() scans the string once in O(n) time, our loop visits every token once, is_integer_literal and int(token) inspect each digit of a token once, and every Python list .append(), .pop(), and 64-bit integer operation runs in O(1) time.
  • Space: O(n) auxiliary memory. The program.split() list holds at most O(n) tokens, and because each token pushes at most one value onto stack or appends at most one value to output, both lists hold at most O(n) integers.

Edge cases

  • Empty or whitespace-only string ("", " \n\t "): program.split() yields [], returning ([], None).
  • Signed numbers vs operators: Bare "+" and "-" run as binary operators, whereas "+8", "-3", "+0", "-0", and "005" push integer literals.
  • Single-item "0 /" vs two-item "8 0 /": "0 /" has only one operand on the stack so it returns "UNDERFLOW", whereas "8 0 /" has two operands with divisor b == 0 so it returns "ZERODIVISION".
  • Preserving earlier output on failure: "+12 PRINT 8 4 4 - / 99 PRINT" stops immediately at "/" and returns ([12], "ZERODIVISION"), ignoring everything after "/".
  • Unconsumed stack values: Leaving values on the stack when the token stream ends ("1 2 3") is valid and returns ([], None).
  • Large 64-bit boundaries: 9223372036854775807 3 / (2^63 - 1 divided by 3) evaluates to exact 3074457345618258602 without floating-point rounding.
  • Malformed tokens: "1.5", "1_000", "0x10", "--5", "+-1", and lowercase "dup" or "print" all trigger "INVALID_TOKEN".

Common mistakes

  • Popping a first and b second. Because b was pushed after a, the first .pop() is b (the right-hand operand); reversing them turns "15 6 -" into -9 and "12 3 /" into 0.
  • Using a // b directly for / on negative numbers. Floor division rounds toward -infinity (-9 // 4 == -3), whereas truncation toward zero drops the fractional part (-2).
  • Using float division int(a / b). Any integer above 2^53 (9,007,199,254,740,992) can lose its low bits when converted to a Python float before dividing.
  • Validating integer literals with try: int(token) or str.isdigit(). int("1_000") accepts underscores, while "²".isdigit() returns True on superscript characters that subsequently crash int().
  • Checking b == 0 (or stack[-1] == 0) before checking len(stack) < 2. That misclassifies "0 /" as "ZERODIVISION" instead of "UNDERFLOW", or crashes with IndexError on "/".
  • Discarding output when returning an error. Every integer emitted by PRINT prior to the failing token must be preserved in the returned list.

Follow-up questions

  • How would you extend the interpreter to support structured control flow such as IF/ELSE branches and WHILE loops? Replace the sequential for token in ... scan with an explicit instruction pointer pc (an integer index into tokens identifying the next instruction to run). Before execution starts, run a single pre-pass with a helper stack to pair each IF with its matching ELSE/THEN and each WHILE with ENDWHILE, recording jump offsets in jump[index] -> target_index and rejecting unbalanced blocks up front. At runtime, IF pops a condition from the operand stack and advances pc past ELSE (or THEN) when the condition is 0, while ENDWHILE jumps pc back to WHILE:

python def match_if_blocks(tokens): """Map IF -> ELSE/THEN and ELSE -> THEN; return None if blocks are unbalanced.""" jump = {} # open_ifs: stack of [if_index, else_index_or_None] open_ifs = [] for idx, token in enumerate(tokens): if token == "IF": open_ifs.append([idx, None]) elif token == "ELSE": if not open_ifs or open_ifs[-1][1] is not None: return None open_ifs[-1][1] = idx elif token == "THEN": if not open_ifs: return None if_idx, else_idx = open_ifs.pop() if else_idx is None: jump[if_idx] = idx else: jump[if_idx] = else_idx jump[else_idx] = idx return None if open_ifs else jump

  • How could you add reusable procedures or macros without letting deep or mutual recursion crash the host runtime? Extract DEF name ... END definitions into a symbol table mapping procedure names to token slices prior to execution. Rather than making recursive Python calls (which hit Python's ~1,000-frame RecursionError), push (token_slice, return_pc) frames onto an explicit call stack list inside your while loop, enforce a hard ceiling like MAX_CALL_DEPTH = 256, and return (output, "CALL_DEPTH_EXCEEDED") when exceeded. If using compile-time text macros instead of runtime calls, build a call graph of macro references first, reject cycles (A expands B which expands A), and cap total expanded tokens so nested macro expansion cannot exhaust memory.
  • How would you bound CPU time, memory growth, and stack depth when running untrusted scripts inside a low-latency embedded worker? Enforce a deterministic execution budget inside the dispatch loop: cap total executed steps (e.g., max_steps = 50_000), operand stack depth (len(stack) <= 1_024), output length (len(output) <= 1_024), and integer range (-2**63 <= val < 2**63 checked after +, -, * so repeated DUP * squaring cannot allocate multi-megabyte Python arbitrary-precision ints!). Poll time.monotonic() (a monotonic clock immune to system clock jumps) once every ~256 steps to enforce wall-clock deadlines cheaply, returning (output, "TIMEOUT") or "STACK_OVERFLOW". In production, run untrusted scripts inside an isolated subprocess or WebAssembly sandbox with OS memory/CPU cgroups so a runaway script can never stall latency-sensitive host threads.

Follow-up questions

Similar questions

More Retell AI interview questions

All 8 Retell AI questions →