Boolean AST Evaluation with Short-Circuiting

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement evaluate(node, env) to compute the bool truth value of a boolean formula tree against a read-only variable mapping env.

Every node in the tree is a Python dict identified by its "type" string:

  • {"type": "literal", "value": bool} — constant boolean leaf whose result is node["value"].
  • {"type": "variable", "name": str} — named symbol leaf whose result is env[node["name"]]. Looking up a symbol absent from env must raise KeyError.
  • {"type": "not", "node": child} — unary negation returning the opposite of child's truth value.
  • {"type": "and", "left": left_child, "right": right_child} — short-circuit conjunction. Evaluate left_child first; when it yields False, immediately yield False and skip right_child altogether. Otherwise yield right_child's truth value.
  • {"type": "or", "left": left_child, "right": right_child} — short-circuit disjunction. Evaluate left_child first; when it yields True, immediately yield True and skip right_child altogether. Otherwise yield right_child's truth value.
def evaluate(node: Dict[str, object], env: Dict[str, bool]) -> bool:

Examples

Example 1

Input:
  node = {
      "type": "and",
      "left": {"type": "variable", "name": "active"},
      "right": {"type": "variable", "name": "missing_flag"},
  }
  env = {"active": False}
Output: False

Walk-through: Reading "active" from env produces False. Because "and" short-circuits as soon as its left operand is False, the right operand ("missing_flag") is never inspected, so no KeyError occurs.

Example 2

Input:
  node = {
      "type": "or",
      "left": {"type": "not", "node": {"type": "literal", "value": False}},
      "right": {"type": "variable", "name": "unset_key"},
  }
  env = {}
Output: True

Walk-through: The left branch negates False into True. Because "or" short-circuits whenever its left operand is True, "unset_key" is skipped and evaluate returns True even though env is empty.

Example 3

Input:
  node = {
      "type": "and",
      "left": {
          "type": "or",
          "left": {"type": "variable", "name": "cached"},
          "right": {"type": "variable", "name": "ready"},
      },
      "right": {"type": "not", "node": {"type": "variable", "name": "locked"}},
  }
  env = {"cached": False, "ready": True, "locked": False}
Output: True

Walk-through: Inside the left "or", "cached" is False, so "ready" is checked next and produces True. Because the left side of "and" succeeded, the right side evaluates not env["locked"] (not False -> True), giving True overall.

Example 4

Input:
  node = {
      "type": "not",
      "node": {
          "type": "and",
          "left": {"type": "literal", "value": True},
          "right": {"type": "variable", "name": "verified"},
      },
  }
  env = {"verified": True}
Output: False

Walk-through: The inner "and" sees True on the left, continues to "verified" (True), and yields True. The outer "not" inverts that result to False.

Constraints

  • Valid "type" strings are "literal", "variable", "not", "and", and "or".
  • Formula trees can have extreme depth (tens of thousands of nested levels), exceeding Python's default call-stack recursion limit.
  • env maps str variable names to bool values and must remain unmodified during evaluate.
  • Any unvisited variable inside a short-circuited right subtree must neither read env nor raise KeyError, whereas any visited variable missing from env must raise KeyError.

Step-by-step walkthrough

  1. Understand the AST nodes and short-circuit rule

    An Abstract Syntax Tree (AST) represents a formula as nested dictionaries where leaves hold boolean constants or variable names and internal nodes hold logical operators ("not", "and", "or"):

    Example 1: And(Variable("active"), Variable("missing_flag")) with env = {"active": False}
    
                 [type: "and"]
                 /           \
      [var: "active"]     [var: "missing_flag"]  <-- MUST NOT be evaluated!
       (False in env)
    

    Each dictionary has a "type" key and node-specific fields: - "literal": yields node["value"] (True or False). - "variable": looks up env[node["name"]], raising KeyError if that name is absent. - "not": evaluates node["node"] and flips True <-> False. - "and": evaluates node["left"] first; when that yields False, immediately produces False without touching node["right"]. - "or": evaluates node["left"] first; when that yields True, immediately produces True without touching node["right"].

    Skipping right when left already settles the outcome is called short-circuiting. Because a skipped subtree might reference an undefined variable, visiting right eagerly or evaluating right ahead of left would wrongly trigger a KeyError.

  2. Start with the clean recursive mental model

    Before handling extreme tree depths, let us look at the natural recursive evaluator so the behavior of each node type is crystal clear:

    def evaluate_recursive(node: dict, env: dict) -> bool:
        node_type = node["type"]
        if node_type == "literal":
            return node["value"]
        if node_type == "variable":
            return env[node["name"]]  # raises KeyError if missing
        if node_type == "not":
            return not evaluate_recursive(node["node"], env)
        if node_type == "and":
            if not evaluate_recursive(node["left"], env):
                return False  # short-circuit: never touch right
            return evaluate_recursive(node["right"], env)
        if node_type == "or":
            if evaluate_recursive(node["left"], env):
                return True  # short-circuit: never touch right
            return evaluate_recursive(node["right"], env)
        raise ValueError(f"Unknown AST node type: {node_type!r}")
    

    Notice two details: - Indexing env[node["name"]] directly (never env.get(...)) raises the exact KeyError required when an evaluated variable is missing. - For "and" and "or", left finishes completely before deciding whether right needs to run.

  3. Why deep trees break plain recursion

    Input formulas may contain tens of thousands of nested operator layers. In Python, every recursive function call pushes a frame onto Python's fixed call stack, which defaults to about 1,000 frames (sys.getrecursionlimit()). On a chain of 50,000 nested "not" or "and" nodes, evaluate_recursive crashes with RecursionError.

    Raising sys.setrecursionlimit is unsafe because we do not know the maximum depth ahead of time, and deep C-level recursion can crash the interpreter outright. Instead, we keep our own stack inside a normal Python list, which lives on the heap and grows cleanly to tens of thousands of nodes.

  4. Simulate recursion with a two-stage explicit stack

    How do we pause a parent node while its first child runs, and then resume the parent afterward? We store (ast_node, stage) tuples on a Last-In, First-Out (LIFO) list stack alongside a variable last_result holding the boolean returned by the most recently finished subtree:

    • VISIT_NODE = 0: We are visiting current for the first time.
      • Leaves ("literal", "variable") compute their boolean and write it directly into last_result.
      • Operators ("not", "and", "or") push (current, AFTER_FIRST_CHILD) onto stack first, and push their first child (first_child, VISIT_NODE) second. Because stack.pop() removes the last pushed item first, the child is guaranteed to run completely before current resumes!
    • AFTER_FIRST_CHILD = 1: The first child has finished, and its boolean sits in last_result.
      • "not": flip last_result = not last_result.
      • "and": if last_result is False, do nothing — last_result is already False, and right is skipped! If last_result is True, then (True and right) equals whatever right evaluates to, so we simply push (current["right"], VISIT_NODE) without pushing current again.
      • "or": mirror image — if last_result is True, skip right and keep True; if last_result is False, push (current["right"], VISIT_NODE) because (False or right) equals right.
    Why pushing parent BEFORE child runs child first (LIFO):
    
      stack.append((And, AFTER_FIRST_CHILD))   -->  bottom: (And, 1)
      stack.append((left, VISIT_NODE))         -->  top:    (left, 0)  <-- popped next!
    
  5. Trace Example 3 and Example 1 step by step

    Consider Example 3: And(Or(Variable("cached"), Variable("ready")), Not(Variable("locked"))) with env = {"cached": False, "ready": True, "locked": False}:

    Step  Popped frame         Action                            last_result  Stack after step (bottom -> top)
    ----  -------------------  --------------------------------  -----------  ------------------------------------
    1     (And, VISIT)         push (And, AFTER), (Or, VISIT)    False        [(And, AFTER), (Or, VISIT)]
    2     (Or, VISIT)          push (Or, AFTER), (cached, V)     False        [(And, AFTER), (Or, AFTER), (cached, V)]
    3     (cached, VISIT)      read env["cached"] -> False       False        [(And, AFTER), (Or, AFTER)]
    4     (Or, AFTER)          left was False -> push (ready, V) False        [(And, AFTER), (ready, VISIT)]
    5     (ready, VISIT)       read env["ready"] -> True         True         [(And, AFTER)]
    6     (And, AFTER)         left was True -> push (Not, V)    True         [(Not, VISIT)]
    7     (Not, VISIT)         push (Not, AFTER), (locked, V)    True         [(Not, AFTER), (locked, VISIT)]
    8     (locked, VISIT)      read env["locked"] -> False       False        [(Not, AFTER)]
    9     (Not, AFTER)         negate False -> True              True         []  (loop ends, return True)
    

    Now compare Example 1, And(Variable("active"), Variable("missing_flag")) with env = {"active": False}: 1. (And, VISIT) pushes (And, AFTER) then (active, VISIT). 2. (active, VISIT) reads env["active"] and sets last_result = False. 3. (And, AFTER) pops, sees last_result is False, and pushes nothing. The stack is now empty, returning False without ever looking up "missing_flag".

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Explicit-stack stages for iterative AST evaluation:
    VISIT_NODE = 0         # First time seeing this node; evaluate its first child next.
    AFTER_FIRST_CHILD = 1  # Its first child just finished; child's boolean is in `last_result`.
    
    
    def evaluate(node: Dict[str, object], env: Dict[str, bool]) -> bool:
        # stack: LIFO list of (ast_node, stage) pairs, replacing Python's ~1,000-frame call stack
        # so deeply nested trees (e.g. 50,000 nodes deep) never raise RecursionError.
        stack: List[Tuple[Dict[str, Any], int]] = [(node, VISIT_NODE)]
    
        # last_result: boolean value produced by the most recently completed subtree.
        last_result = False
    
        while stack:
            current, stage = stack.pop()
            node_type = current["type"]
    
            # Base case 1: boolean constant leaf.
            if node_type == "literal":
                last_result = current["value"]
    
            # Base case 2: variable lookup leaf. Direct `env[...]` raises KeyError when missing.
            elif node_type == "variable":
                var_name = current["name"]
                last_result = env[var_name]
    
            # Unary NOT: evaluate child first, then negate `last_result` on return.
            elif node_type == "not":
                if stage == VISIT_NODE:
                    # Push parent resume frame BEFORE child so LIFO order runs child first.
                    stack.append((current, AFTER_FIRST_CHILD))
                    stack.append((current["node"], VISIT_NODE))
                else:
                    last_result = not last_result
    
            # Short-circuit AND: evaluate `left` first; touch `right` ONLY if `left` was True.
            elif node_type == "and":
                if stage == VISIT_NODE:
                    stack.append((current, AFTER_FIRST_CHILD))
                    stack.append((current["left"], VISIT_NODE))
                elif last_result:
                    # Since (True and right) == right, `right`'s value becomes the whole And's value;
                    # no further resume frame for `current` is needed.
                    stack.append((current["right"], VISIT_NODE))
                # If last_result is False, short-circuit: leave last_result as False and skip `right`.
    
            # Short-circuit OR: evaluate `left` first; touch `right` ONLY if `left` was False.
            elif node_type == "or":
                if stage == VISIT_NODE:
                    stack.append((current, AFTER_FIRST_CHILD))
                    stack.append((current["left"], VISIT_NODE))
                elif not last_result:
                    # Since (False or right) == right, `right`'s value becomes the whole Or's value.
                    stack.append((current["right"], VISIT_NODE))
                # If last_result is True, short-circuit: leave last_result as True and skip `right`.
    
            else:
                raise ValueError(f"Unknown AST node type: {node_type!r}")
    
        return last_result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of evaluating a formula Abstract Syntax Tree (AST) — a tree structure where leaf nodes are inputs and branch nodes are operators — like walking through an amusement-park safety checklist. An AND branch requires two rules to pass ("Has valid ticket AND meets height limit"): if the rider has no ticket, the attendant immediately says "No" without ever reaching for the measuring tape, even if the measuring tape is missing. An OR branch requires just one rule to pass ("Has VIP pass OR waited in the main line"): as soon as the VIP pass checks out, the rider walks straight in without checking the second rule. Skipping unnecessary second checks is called short-circuit evaluation.

Two pitfalls break naive solutions here. First, evaluating both children before combining them (left_val = evaluate(left); right_val = evaluate(right); return left_val and right_val) visits skipped branches and crashes with KeyError on undefined variables that should never have been looked up. Second, writing a plain recursive function uses Python's call stack — the fixed-depth internal memory tracking active function calls — which hits a RecursionError around 1,000 nested levels on tall operator chains.

Instead, we simulate recursion manually using our own LIFO (Last-In, First-Out) stack, a plain Python list where the last item pushed is the first item popped, storing (node, stage) pairs and a last_result variable. Let us trace Example 1 (And(Variable("active"), Variable("missing_flag")) with env = {"active": False}): 1. Pop (And, VISIT_NODE): push (And, AFTER_FIRST_CHILD) first, then push (Variable("active"), VISIT_NODE) on top so the left child runs first. 2. Pop (Variable("active"), VISIT_NODE): look up env["active"] and set last_result = False. 3. Pop (And, AFTER_FIRST_CHILD): see last_result is False, so do not push Variable("missing_flag"). 4. The stack is now empty, returning False safely without ever touching "missing_flag".

Complexity

Let N be the total number of nodes in the AST and H be the height of the tree (the length of the longest root-to-leaf path, where H <= N).

  • Time: O(N). Each visited leaf node is pushed and popped once (VISIT_NODE), and each visited operator node is pushed and popped at most twice (VISIT_NODE and AFTER_FIRST_CHILD), doing O(1) dictionary lookups at each step. Short-circuiting only skips subtrees, so worst-case work visits all N nodes in O(N) time.
  • Space: O(H). At any moment, stack holds at most one AFTER_FIRST_CHILD entry per ancestor along the active root-to-leaf path (and doesn't even keep "and"/"or" ancestors while evaluating their right child!), so stack space never exceeds O(H), with O(N) only when the entire tree is a single skinny chain.

Edge cases

  • Single leaf root (Literal(True) or Variable("active")): The while loop executes a single iteration and returns the boolean value directly.
  • Missing variable on an evaluated branch: Direct dictionary indexing env[var_name] raises KeyError whenever a missing variable is actually reached (e.g., And(Literal(True), Variable("missing")) or Not(Variable("missing"))).
  • Missing variable inside a short-circuited subtree at any depth: Never visited and raises no error (for example, Not(And(Literal(False), Variable("unset_key"))) cleanly returns True).
  • Deeply nested chains (30,000–50,000+ levels): Handled effortlessly in heap memory without hitting Python's RecursionError limit.
  • Shared DAG subtrees (same node dict referenced twice): Safe because nodes and env are read-only and never mutated during traversal.

Common mistakes

  • Evaluating both subtrees before applying Python's and/or: Writing return evaluate(left, env) and evaluate(right, env) works in recursion because Python short-circuits the second call, unless you assign right_val = evaluate(right, env) to a variable beforehand — which forces right to run unconditionally and triggers false KeyErrors.
  • Pushing left before right or child before parent on an explicit stack: Because a stack is Last-In, First-Out, pushing left and then right pops right first! Evaluating right before left breaks left-to-right short-circuiting on And(Variable("active"), Variable("missing_flag")).
  • Using env.get(var_name) instead of env[var_name]: dict.get returns None (falsy) instead of raising KeyError, silently turning missing variables into False.
  • Looking up "left" on a "not" node: Unary "not" stores its child under the key "node", whereas binary "and" and "or" use "left" and "right".

Alternative approaches

  • Direct recursion: As shown in steps.md, a 15-line recursive function is the cleanest solution when tree height is guaranteed to be under a few hundred levels, and is great to write first before converting to an explicit stack for deep trees.
  • Bytecode compilation with jump offsets: Flatten the AST once into an array of simple instructions (LOAD_VAR, NOT, JUMP_IF_FALSE target, JUMP_IF_TRUE target). Evaluating against an environment then walks an integer instruction pointer forward with zero stack pushes or pops.

Follow-up questions

  • How could we support numeric operands alongside relational nodes such as > or ==? Allow last_result and env to hold either bool or int values, and add node types such as {"type": "int", "value": 5} and {"type": "gt", "left": ..., "right": ...}. Because relational comparisons do not short-circuit, both children must run: on our explicit stack, "gt" uses three stages — stage 0 pushes (current, 1) and left; stage 1 saves left_val = last_result into (current, 2, left_val) and pushes right; stage 2 verifies that both left_val and last_result are integers (excluding bool, since isinstance(True, int) is True in Python!) and sets last_result = left_val > last_result.
  • What must change if nodes can mutate variable bindings mid-evaluation, like inline assignments? Short-circuiting and strict left-to-right order become even more critical because an assignment inside a skipped right branch (such as False and (flag := True)) must not modify flag! Copy env up front if the caller expects their original mapping to stay unchanged, then mutate the working copy in place whenever an "assign" node finishes evaluating its right-hand expression. Subtree caching also stops working within a single run because reading Variable("flag") before and after an assignment can return different values.
  • How can repeated evaluations of one fixed AST across many distinct variable maps be accelerated? First apply constant folding — pre-simplifying subtrees whose values do not depend on env, such as replacing And(Literal(False), anything) with Literal(False) or Not(Not(x)) with x (while taking care not to fold And(x, Literal(False)) into False, because x could still raise KeyError!). Second, compile the simplified AST into a flat bytecode array with conditional jump offsets to eliminate tree-walking overhead. Finally, use memoization — caching a subtree's result (or KeyError outcome) keyed by the tuple of values of only the specific variables referenced inside that subtree — so two variable maps that differ only on unrelated keys reuse the cached answer in O(1) time.

Follow-up questions

Similar questions

More Sigmacomputing interview questions

All 4 Sigmacomputing questions →