Variadic Prefix Expression Evaluator

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Write a function evaluate(expr) that computes the integer value of a nested prefix expression. Each valid expression is either:

  • A standalone integer literal (int, excluding bool), which evaluates to itself, or
  • A non-empty Python list [op, operand_1, operand_2, ...], where op is "+" or "-" and every operand is itself an integer literal or a nested expression list.

Operator rules depend on both the symbol and how many operands follow it:

  • Addition ("+"): Accepts zero or more operands and returns their sum. When given zero operands (["+"]), return the additive identity 0.
  • Subtraction ("-"): Requires at least one operand:
    • One operand (["-", x]): Returns the arithmetic negation -x.
    • Two or more operands (["-", x_1, x_2, ..., x_k]): Subtracts left to right starting from x_1, computing ((x_1 - x_2) - ...) - x_k.
    • Zero operands (["-"]): Invalid; raise ValueError.

Validate the entire structure during evaluation and raise ValueError whenever:

  • Any expression list has length 0 ([]),
  • Position 0 of a list is anything other than "+" or "-", or
  • The top-level input or any operand is neither a list nor a genuine int (True and False must be rejected even though bool subclasses int in Python).
from typing import Union


def evaluate(expr: Union[int, list]) -> int:
    ...

Examples

Example 1

Input:  expr = ["+", 6, -2, 9, 4]
Output: 17

All four operands are summed in order: 6 + (-2) + 9 + 4 = 17.

Example 2

Input:  expr = ["-", 25, 8, 4]
Output: 13

With multiple operands, "-" groups from the left: (25 - 8) - 4 = 17 - 4 = 13.

Example 3

Input:  expr = ["-", ["+", 12, 3], ["-", 6], ["+"]]
Output: 21

First ["+", 12, 3] produces 15, single-operand ["-", 6] negates 6 to -6, and zero-operand ["+"] yields 0. Folding the outer "-" from left to right gives (15 - (-6)) - 0 = 21.

Constraints

  • Total items across all nested lists (N): 1 <= N <= 10^5.
  • Every integer literal in the input fits in signed 32-bit bounds (-2^31 <= x <= 2^31 - 1), though intermediate sums or differences may exceed 32 bits.
  • Maximum list nesting depth (D): 0 <= D <= 1000.
  • Time complexity: O(N).
  • Auxiliary space complexity: O(D).

Step-by-step walkthrough

  1. Understand prefix expressions and the three "-" cases

    We want to evaluate nested prefix expressions (expressions where the operator comes before its operands, like ["+", 6, -2, 9, 4]) where operators are variadic (meaning they accept a variable number of operands rather than always two).

    Every valid expression is either a plain integer or a nested tree of lists:

             ["-", ["+", 12, 3], ["-", 6], ["+"]]    -->  (15 - (-6)) - 0 = 21
                   /              |          \
            ["+", 12, 3]       ["-", 6]     ["+"]
              /      \            |           |
            12        3           6           0 (empty sum -> 0)
                          (unary negation -> -6)
    

    Let's check every operator rule and error condition before writing code:

    • Addition ("+"): Sums all operands left to right. Zero operands is valid and returns the additive identity: ["+"] -> 0, ["+", 9] -> 9, ["+", 6, -2, 9, 4] -> 17.
    • Subtraction ("-"): Has three distinct behaviors depending on operand count:
      • 0 operands (["-"]): invalid -> raise ValueError.
      • 1 operand (["-", a]): unary negation -> -a (for example, ["-", 6] -> -6).
      • 2+ operands (["-", a, b, c]): left-associative subtraction (grouped from the left) -> ((a - b) - c).
    • Invalid inputs (ValueError): Empty list [], unsupported operator (like "*" or [1, 2]), or any operand/top-level value that is neither a list nor an integer. Watch out for a classic Python quirk: bool is a subclass of int (isinstance(True, int) is True!), so we must reject True and False explicitly.
  2. Start with natural recursion, then spot the stack-depth trap

    Because nested lists form a tree, recursion is the first idea most engineers write. Notice one crucial space detail right away: if a single list has 99,999 integers (["+", 1, 1, ..., 1]), building a temporary list [evaluate(x) for x in expr[1:]] would allocate O(N) memory even at depth D = 1, breaking the O(D) auxiliary space limit! Instead, we must fold each operand into a single running integer as soon as it finishes:

    def evaluate_recursive_draft(expr):
        if not isinstance(expr, list):
            if isinstance(expr, bool) or not isinstance(expr, int):
                raise ValueError("Invalid integer")
            return expr
        if len(expr) == 0 or expr[0] not in ("+", "-"):
            raise ValueError("Invalid expression list")
    
        op = expr[0]
        if op == "+":
            total = 0
            for i in range(1, len(expr)):
                total += evaluate_recursive_draft(expr[i])
            return total
    
        if len(expr) == 1:
            raise ValueError("'-' requires at least one operand")
        first = evaluate_recursive_draft(expr[1])
        if len(expr) == 2:
            return -first
        for i in range(2, len(expr)):
            first -= evaluate_recursive_draft(expr[i])
        return first
    

    Why does this recursive draft fail our constraints? CPython caps its function call stack at sys.getrecursionlimit() frames — 1000 by default — and that 1000-frame budget includes the test harness and caller frames already on the stack when evaluate() is called. On a valid expression nested 1000 lists deep (["-", ["-", ...]]), plain recursion crashes with RecursionError: maximum recursion depth exceeded.

  3. Replace the call stack with an explicit Frame stack

    Instead of relying on Python's C call stack, we manage our own stack in a plain Python list (which lives on the heap and is limited only by available RAM). Each entry on stack is a tiny Frame object representing one currently open expression list along the path from the root down to the current sub-expression:

    Active expression path:       Explicit `stack` (at most D frames):
      root: ["-", ..., ...]   ->   stack[0]: Frame(op="-", next_index=2, count=1, running=15)
                 \
            child: ["-", 6]   ->   stack[1]: Frame(op="-", next_index=2, count=1, running=6)  <-- top
    

    To keep every Frame strictly O(1) in memory: - Store a reference to expr plus an integer cursor next_index (starting at 1), never slicing expr[1:] (which would copy up to N pointers). - Store running_value (the integer accumulated so far) and operand_count (how many operands have been folded into running_value).

  4. Validate inputs and handle unary vs. multi-operand "-"

    Tracking operand_count inside Frame lets us unify all three "-" cases cleanly without peeking ahead:

    • In __init__: reject len(expr) == 0, op not in OPERATORS, and op == "-" and len(expr) == 1 (["-"]). Notice OPERATORS = ("+", "-") is a tuple rather than a set or dict: if someone passes an unhashable list in the operator slot like [["+"], 1], checking op not in ("+", "-") compares with == and raises the required ValueError instead of crashing with TypeError: unhashable type: 'list'.
    • In fold_operand(value):
      • For "+", always add value to running_value (which starts at 0, so ["+"] naturally finishes at 0).
      • For "-", when operand_count == 0 (the first operand a), set running_value = value (+a). For every later operand (operand_count >= 1), subtract value (running_value -= value), producing ((a - b) - c).
    • In finish(): once all operands are read, check if self.op == "-" and self.operand_count == 1:. If only one operand a was ever folded, return -self.running_value (-a); otherwise return self.running_value directly.
    OPERATORS = ("+", "-")
    
    
    def validate_integer(value) -> int:
        """Return value if it is a true Python int, or raise ValueError otherwise."""
        # In Python, bool is a subclass of int (isinstance(True, int) is True),
        # so we must reject booleans explicitly before checking isinstance(value, int).
        if isinstance(value, bool) or not isinstance(value, int):
            raise ValueError(f"Operand must be an integer or expression list, got: {value!r}")
        return value
    
    
    class Frame:
        """State for one active expression list `[op, operand_1, ...]` on the evaluation stack.
    
        Mini-shape: Frame(expr_ref, op="+"|"-", next_index=1..len(expr), operand_count=0.., running_value=int)
        """
    
        def __init__(self, expr: list):
            # Validate list-level syntax immediately when entering the sub-expression.
            if len(expr) == 0:
                raise ValueError("Expression list cannot be empty")
    
            op = expr[0]
            if op not in OPERATORS:
                raise ValueError(f"Unsupported operator: {op!r}")
    
            # "+" allows zero operands (["+"] == 0), whereas "-" requires at least one operand.
            if op == "-" and len(expr) == 1:
                raise ValueError("Operator '-' requires at least one operand")
    
            # Keep a reference to `expr` rather than slicing `expr[1:]` so frame space stays O(1).
            self.expr = expr
            self.op = op
            self.next_index = 1       # Index of the next unread operand inside `self.expr`
            self.operand_count = 0    # Number of evaluated operands folded so far
            self.running_value = 0    # Accumulator updated left-to-right as operands finish
    
        def has_more_operands(self) -> bool:
            return self.next_index < len(self.expr)
    
        def next_operand(self):
            operand = self.expr[self.next_index]
            self.next_index += 1
            return operand
    
        def fold_operand(self, value: int) -> None:
            """Combine the next evaluated operand `value` into `self.running_value` left to right."""
            if self.op == "+":
                self.running_value += value
            elif self.operand_count == 0:
                # For "-", the first operand seeds the accumulator (+a) so subsequent operands
                # compute ((a - b) - c) instead of subtracting `a` from 0.
                self.running_value = value
            else:
                self.running_value -= value
            self.operand_count += 1
    
        def finish(self) -> int:
            """Produce the final integer value once all operands in `self.expr` have been folded."""
            # Unary minus `["-", a]` seeded `running_value = a` with operand_count == 1; negate it here.
            # Binary/variadic minus (`operand_count >= 2`) already subtracted later operands from `a`.
            if self.op == "-" and self.operand_count == 1:
                return -self.running_value
            return self.running_value
    
  5. Write the iterative evaluation loop

    Now evaluate(expr) handles a bare non-list input up front, then runs a simple while stack: loop looking at current_frame = stack[-1]:

    1. Still has unread operands (current_frame.has_more_operands()): Read the next operand. If it is a nested list, push a new Frame(operand) onto stack so the child evaluates first while current_frame waits underneath. Otherwise validate that it is an integer and fold it directly into current_frame.
    2. No operands left: Finalize sub_result = current_frame.finish() and pop current_frame. If stack is now empty, sub_result is the answer for the whole expression; otherwise fold sub_result into the waiting parent frame stack[-1].
    from typing import Union
    
    
    def evaluate(expr: Union[int, list]) -> int:
        # Base case: a bare top-level token (e.g., `evaluate(7)`) skips the stack after validation.
        if not isinstance(expr, list):
            return validate_integer(expr)
    
        # Explicit call stack of active Frame objects along the current root-to-node path.
        # Using a Python list avoids CPython's ~1000-frame recursion limit while using O(D) space.
        stack = [Frame(expr)]
    
        while stack:
            current_frame = stack[-1]
    
            # Phase 1: If the top frame still has unread operands, advance by one operand.
            if current_frame.has_more_operands():
                operand = current_frame.next_operand()
                if isinstance(operand, list):
                    # Nested expression list: pause `current_frame` and evaluate the child first.
                    stack.append(Frame(operand))
                else:
                    # Leaf operand: validate that it is a true int and fold it immediately.
                    current_frame.fold_operand(validate_integer(operand))
    
            # Phase 2: All operands of `current_frame` are done; finalize and pop it.
            else:
                sub_result = current_frame.finish()
                stack.pop()
                if not stack:
                    return sub_result
                # Feed the completed sub-expression's integer value into its waiting parent frame.
                stack[-1].fold_operand(sub_result)
    
        # Unreachable because stack starts non-empty and returns when the root frame pops.
        raise AssertionError("Unreachable empty stack state")
    
  6. Trace Example 3 step by step on the stack

    Let's trace expr = ["-", ["+", 12, 3], ["-", 6], ["+"]] (writing each frame as F(op, idx, count, val)):

    Step  Action                                        Stack (bottom -> top)
    ----  --------------------------------------------  ----------------------------------------------
    1     Start with root list                          [F("-", idx=1, count=0, val=0)]
    2     Root reads ["+", 12, 3] -> push child         [F("-", idx=2, count=0, val=0),
                                                         F("+", idx=1, count=0, val=0)]
    3     Child "+" folds 12, then folds 3              [F("-", idx=2, count=0, val=0),
                                                         F("+", idx=3, count=2, val=15)]
    4     Child "+" finishes -> 15; pop & fold into F0  [F("-", idx=2, count=1, val=15)]   (first operand seeds +15)
    5     Root reads ["-", 6] -> push child             [F("-", idx=3, count=1, val=15),
                                                         F("-", idx=1, count=0, val=0)]
    6     Child "-" folds 6                             [F("-", idx=3, count=1, val=15),
                                                         F("-", idx=2, count=1, val=6)]
    7     Child "-" finishes (count==1 -> -6); fold     [F("-", idx=3, count=2, val=21)]   (15 - (-6) = 21)
    8     Root reads ["+"] -> push child, finish -> 0   [F("-", idx=4, count=3, val=21)]   (21 - 0 = 21)
    9     Root finishes (count==3 -> 21); stack empty   return 21
    

    Notice stack never held more than 2 frames — matching the nesting depth D = 2 — and no sub-list was ever copied.

  7. Complete solution

    from typing import Union
    
    # Use a tuple rather than a set/dict for membership checks so unhashable elements
    # like a nested list in operator position (e.g., [["+"], 1]) compare cleanly with `==`
    # and raise ValueError instead of TypeError: unhashable type: 'list'.
    OPERATORS = ("+", "-")
    
    
    def validate_integer(value) -> int:
        """Return value if it is a true Python int, or raise ValueError otherwise."""
        # In Python, bool is a subclass of int (isinstance(True, int) is True),
        # so we must reject booleans explicitly before checking isinstance(value, int).
        if isinstance(value, bool) or not isinstance(value, int):
            raise ValueError(f"Operand must be an integer or expression list, got: {value!r}")
        return value
    
    
    class Frame:
        """State for one active expression list `[op, operand_1, ...]` on the evaluation stack.
    
        Mini-shape: Frame(expr_ref, op="+"|"-", next_index=1..len(expr), operand_count=0.., running_value=int)
        """
    
        def __init__(self, expr: list):
            # Validate list-level syntax immediately when entering the sub-expression.
            if len(expr) == 0:
                raise ValueError("Expression list cannot be empty")
    
            op = expr[0]
            if op not in OPERATORS:
                raise ValueError(f"Unsupported operator: {op!r}")
    
            # "+" allows zero operands (["+"] == 0), whereas "-" requires at least one operand.
            if op == "-" and len(expr) == 1:
                raise ValueError("Operator '-' requires at least one operand")
    
            # Keep a reference to `expr` rather than slicing `expr[1:]` so frame space stays O(1).
            self.expr = expr
            self.op = op
            self.next_index = 1       # Index of the next unread operand inside `self.expr`
            self.operand_count = 0    # Number of evaluated operands folded so far
            self.running_value = 0    # Accumulator updated left-to-right as operands finish
    
        def has_more_operands(self) -> bool:
            return self.next_index < len(self.expr)
    
        def next_operand(self):
            operand = self.expr[self.next_index]
            self.next_index += 1
            return operand
    
        def fold_operand(self, value: int) -> None:
            """Combine the next evaluated operand `value` into `self.running_value` left to right."""
            if self.op == "+":
                self.running_value += value
            elif self.operand_count == 0:
                # For "-", the first operand seeds the accumulator (+a) so subsequent operands
                # compute ((a - b) - c) instead of subtracting `a` from 0.
                self.running_value = value
            else:
                self.running_value -= value
            self.operand_count += 1
    
        def finish(self) -> int:
            """Produce the final integer value once all operands in `self.expr` have been folded."""
            # Unary minus `["-", a]` seeded `running_value = a` with operand_count == 1; negate it here.
            # Binary/variadic minus (`operand_count >= 2`) already subtracted later operands from `a`.
            if self.op == "-" and self.operand_count == 1:
                return -self.running_value
            return self.running_value
    
    
    def evaluate(expr: Union[int, list]) -> int:
        # Base case: a bare top-level token (e.g., `evaluate(7)`) skips the stack after validation.
        if not isinstance(expr, list):
            return validate_integer(expr)
    
        # Explicit call stack of active Frame objects along the current root-to-node path.
        # Using a Python list avoids CPython's ~1000-frame recursion limit while using O(D) space.
        stack = [Frame(expr)]
    
        while stack:
            current_frame = stack[-1]
    
            # Phase 1: If the top frame still has unread operands, advance by one operand.
            if current_frame.has_more_operands():
                operand = current_frame.next_operand()
                if isinstance(operand, list):
                    # Nested expression list: pause `current_frame` and evaluate the child first.
                    stack.append(Frame(operand))
                else:
                    # Leaf operand: validate that it is a true int and fold it immediately.
                    current_frame.fold_operand(validate_integer(operand))
    
            # Phase 2: All operands of `current_frame` are done; finalize and pop it.
            else:
                sub_result = current_frame.finish()
                stack.pop()
                if not stack:
                    return sub_result
                # Feed the completed sub-expression's integer value into its waiting parent frame.
                stack[-1].fold_operand(sub_result)
    
        # Unreachable because stack starts non-empty and returns when the root frame pops.
        raise AssertionError("Unreachable empty stack state")
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine evaluating nested parentheses using a stack of sticky notes on your desk. Each time you encounter a bracketed prefix expression (an expression where the operator appears first, like ["+", 12, 3]), you place a new sticky note on top of the pile recording the operator, which item index you are reading next, how many operands you have combined so far, and the running total. Whenever an inner list finishes all of its items, you tear off that top note and fold its single resulting number into the waiting note directly underneath.

Two obvious approaches fall short of the constraints here. Writing a standard recursive function hits CPython's default 1000-frame call-stack limit (RecursionError) on inputs nested 1000 levels deep, because the caller's own stack frames already consume part of those 1000 slots. Meanwhile, slicing sub-lists (expr[1:]) or collecting evaluated operands into a temporary list ([evaluate(x) for x in expr[1:]]) allocates up to O(N) extra memory on wide expressions like ["+", 1, 1, ..., 1], breaking the O(D) auxiliary space requirement.

Using an explicit Python list of tiny Frame objects (stack) solves both problems at once. Walk through ["-", ["+", 12, 3], ["-", 6], ["+"]]: 1. Push a root "-" frame. Its first operand is ["+", 12, 3], so push a "+" frame on top. 2. The "+" frame folds 12 and 3 into running_value = 15, pops, and hands 15 to the root "-" frame (since operand_count == 0, root sets running_value = 15, operand_count = 1). 3. Root's second operand is ["-", 6], so push a "-" frame. It folds 6 (operand_count = 1), sees operand_count == 1 in finish(), and negates 6 to return -6; root subtracts -6 (15 - (-6) = 21, operand_count = 2). 4. Root's third operand ["+"] pushes a "+" frame with zero operands that immediately finishes with 0; root folds 21 - 0 = 21 (operand_count = 3) and returns 21.

Complexity

  • Time: O(N), where N is the total number of tokens (operators, integers, and sub-lists) across the entire nested structure. Every sub-list creates exactly one Frame and is popped once, and every operand is read once by next_operand() and folded in O(1) constant time without copying any list. (Even 10^5 maximal 32-bit integers sum to less than 2^48, so integer arithmetic stays constant-time.)
  • Auxiliary space: O(D), where D is the maximum nesting depth. At any point, stack only holds one Frame per open list along the single active path from the root to the current element — never sibling lists that already finished — and each Frame stores only a pointer to expr plus four scalar fields (O(1) per frame).

Edge cases

  • Bare top-level integer (or invalid top-level scalar): evaluate(7) returns 7 directly without creating a Frame, while evaluate(True), evaluate("5"), or evaluate(None) still runs through validate_integer and raises ValueError.
  • Zero-operand "+" vs. zero-operand "-": ["+"] legally returns 0 (and ["-", ["+"]] returns 0), whereas ["-"] raises ValueError even when buried deep inside a larger valid expression like ["+", 1, ["-", 2, ["-"]]].
  • Unary negation vs. left-associative subtraction: ["-", 6] returns -6, whereas ["-", 25, 8, 4] evaluates left-to-right as (25 - 8) - 4 = 13 (a left-associative operator groups from the left, not 25 - (8 - 4) = 21).
  • Unhashable token in operator position: An input like [["+"], 1] has a list at expr[0]. Checking op not in ("+", "-") against a tuple uses == and cleanly raises ValueError, whereas op not in {"+": ...} against a dict or set would crash with TypeError: unhashable type: 'list'.
  • Python booleans (True / False): Because bool subclasses int in Python (isinstance(True, int) is True), validate_integer checks isinstance(value, bool) first so ["+", True, 1] raises ValueError instead of silently returning 2.
  • 32-bit integer overflow boundaries: Inputs fit in signed 32-bit integers (-2^31 to 2^31 - 1), so ["-", -2147483648] (2147483648) and ["+", 2147483647, 2147483647] (4294967294) exceed 32 bits. Python's arbitrary-precision int handles this automatically; in C++ or Java you would use a 64-bit long accumulator.
  • Shared vs. cyclic list references: Reusing the same sub-list object twice (sub = ["+", 1, 2]; evaluate(["+", sub, sub])) works fine (6). If untrusted Python callers could construct a self-referential cycle (a = ["+"]; a.append(a)), tracking active id(expr) values in a set alongside stack (O(D) space) catches cycles in O(1) per push.

Common mistakes

  • Using plain recursion without checking Python's stack limit: Depth 1000 exceeds CPython's default 1000-frame call stack once test-runner frames are included, raising RecursionError.
  • Collecting operand results into a list or slicing expr[1:]: Allocating a values list or slicing expr[1:] on ["+", 1, 1, ..., 1] turns O(D) extra space into O(N) extra space (and slicing inside recursion can even turn time into O(N^2)).
  • Subtracting the first operand from 0 on multi-operand "-": Initializing acc = 0 and running acc -= value on every operand turns ["-", 25, 8, 4] into -25 - 8 - 4 = -37 instead of (25 - 8) - 4 = 13.
  • Evaluating subtraction right-to-left: Computing first - evaluate(["-"] + rest) evaluates 25 - (8 - 4) = 21 instead of (25 - 8) - 4 = 13.
  • Letting IndexError or TypeError leak out: Accessing expr[0] before checking len(expr) == 0, or hashing expr[0] in a dict before checking isinstance(op, str), raises the wrong exception type instead of ValueError.

Follow-up questions

  • How could you decouple operator rules from tree traversal so adding variadic operators such as "*", "/", or "max" requires no changes to the stack loop? Extract the operator-specific math out of Frame into an OperatorSpec registry (REGISTRY: dict[str, OperatorSpec]), where each operator defines min_operands, fold(acc, value, count) -> int, and finish(acc, count) -> int. In Frame.__init__, first verify isinstance(op, str) and op in REGISTRY (checking isinstance(op, str) prevents TypeError on unhashable expr[0]) and verify len(expr) - 1 >= spec.min_operands. The stack loop in evaluate() never changes at all when new operators are added: "*" sets min_operands = 0 (returning the multiplicative identity 1 when count == 0), "max" sets min_operands = 1 and tracks the largest value seen, and "/" sets min_operands = 2 (or 1 if unary reciprocal 1 // a is desired), specifies truncation vs. floor division explicitly, and raises ValueError if any divisor is 0.

  • What happens when expression nesting goes far beyond Python's call-stack limit (for instance, 100,000 levels deep), and how does an iterative evaluator handle it? Our Frame-stack implementation is already purely iterative! Because stack is a standard heap-allocated Python list rather than the C call stack, 10^5 nested lists simply push 10^5 small Frame objects (~15–20 MB in CPython) without touching sys.getrecursionlimit(). At depths above 10^5, watch out for the surrounding infrastructure in production: built-in recursive serializers/parsers like json.loads, repr(expr), or copy.deepcopy(expr) will themselves hit RecursionError on 10^5-deep trees unless replaced with streaming/iterative parsers and a hard max-depth cap on untrusted requests.

  • If short-circuiting logical operators such as "AND" and "OR" were added, how would you skip evaluating unneeded sub-expressions? Short-circuit evaluation (stopping as soon as the final answer is determined, such as skipping the rest of "AND" once any operand evaluates to False) requires only a one-line hook in Frame: let fold_operand(value) return a done: bool flag (or advance self.next_index = len(self.expr)) as soon as a deciding value arrives (False for "AND", True for "OR"). Because our loop evaluates operands one at a time on demand rather than pre-evaluating all children, any remaining sub-lists in self.expr are never even pushed onto stack! One subtle product decision to clarify with your interviewer is error handling on skipped branches (for example, ["AND", False, ["UNKNOWN_OP"]]): if malformed syntax in skipped branches must still raise ValueError, run a separate iterative O(N) syntax-validation pass before evaluating; if full lazy evaluation (delaying computation of an expression until its value is actually needed, often wrapped in an unevaluated object called a thunk) is wanted, skipped branches intentionally stay untouched just like Python's False and (1 / 0).

Alternative approaches

  • Recursion with O(1) per-call accumulators: Clean and ~25 lines shorter when max depth is guaranteed well below 1000 (say D <= 500), since each call frame holds only op, loop index i, and running_value, but fails at D = 1000 under CPython's default stack limit unless sys.setrecursionlimit is mutated globally.
  • Lightweight [expr, next_index, count, running_value] list tuples instead of a Frame class: Uses the exact same iterative algorithm with slightly lower per-frame object overhead in Python, at the cost of less self-documenting code (frame[3] instead of frame.running_value).

Follow-up questions

Similar questions

More Anduril interview questions

All 7 Anduril questions →