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 isnode["value"].{"type": "variable", "name": str}— named symbol leaf whose result isenv[node["name"]]. Looking up a symbol absent fromenvmust raiseKeyError.{"type": "not", "node": child}— unary negation returning the opposite ofchild's truth value.{"type": "and", "left": left_child, "right": right_child}— short-circuit conjunction. Evaluateleft_childfirst; when it yieldsFalse, immediately yieldFalseand skipright_childaltogether. Otherwise yieldright_child's truth value.{"type": "or", "left": left_child, "right": right_child}— short-circuit disjunction. Evaluateleft_childfirst; when it yieldsTrue, immediately yieldTrueand skipright_childaltogether. Otherwise yieldright_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.
envmapsstrvariable names toboolvalues and must remain unmodified duringevaluate.- Any unvisited variable inside a short-circuited right subtree must neither read
envnor raiseKeyError, whereas any visited variable missing fromenvmust raiseKeyError.
Step-by-step walkthrough
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": yieldsnode["value"](TrueorFalse). -"variable": looks upenv[node["name"]], raisingKeyErrorif that name is absent. -"not": evaluatesnode["node"]and flipsTrue<->False. -"and": evaluatesnode["left"]first; when that yieldsFalse, immediately producesFalsewithout touchingnode["right"]. -"or": evaluatesnode["left"]first; when that yieldsTrue, immediately producesTruewithout touchingnode["right"].Skipping
rightwhenleftalready settles the outcome is called short-circuiting. Because a skipped subtree might reference an undefined variable, visitingrighteagerly or evaluatingrightahead ofleftwould wrongly trigger aKeyError.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 (neverenv.get(...)) raises the exactKeyErrorrequired when an evaluated variable is missing. - For"and"and"or",leftfinishes completely before deciding whetherrightneeds to run.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_recursivecrashes withRecursionError.Raising
sys.setrecursionlimitis 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 Pythonlist, which lives on the heap and grows cleanly to tens of thousands of nodes.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) liststackalongside a variablelast_resultholding the boolean returned by the most recently finished subtree:VISIT_NODE = 0: We are visitingcurrentfor the first time.- Leaves (
"literal","variable") compute their boolean and write it directly intolast_result. - Operators (
"not","and","or") push(current, AFTER_FIRST_CHILD)ontostackfirst, and push their first child(first_child, VISIT_NODE)second. Becausestack.pop()removes the last pushed item first, the child is guaranteed to run completely beforecurrentresumes!
- Leaves (
AFTER_FIRST_CHILD = 1: The first child has finished, and its boolean sits inlast_result."not": fliplast_result = not last_result."and": iflast_resultisFalse, do nothing —last_resultis alreadyFalse, andrightis skipped! Iflast_resultisTrue, then(True and right)equals whateverrightevaluates to, so we simply push(current["right"], VISIT_NODE)without pushingcurrentagain."or": mirror image — iflast_resultisTrue, skiprightand keepTrue; iflast_resultisFalse, push(current["right"], VISIT_NODE)because(False or right)equalsright.
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!Trace Example 3 and Example 1 step by step
Consider Example 3:
And(Or(Variable("cached"), Variable("ready")), Not(Variable("locked")))withenv = {"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"))withenv = {"active": False}: 1.(And, VISIT)pushes(And, AFTER)then(active, VISIT). 2.(active, VISIT)readsenv["active"]and setslast_result = False. 3.(And, AFTER)pops, seeslast_resultisFalse, and pushes nothing. The stack is now empty, returningFalsewithout ever looking up"missing_flag".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_NODEandAFTER_FIRST_CHILD), doing O(1) dictionary lookups at each step. Short-circuiting only skips subtrees, so worst-case work visits allNnodes in O(N) time. - Space: O(H). At any moment,
stackholds at most oneAFTER_FIRST_CHILDentry 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)orVariable("active")): Thewhileloop executes a single iteration and returns the boolean value directly. - Missing variable on an evaluated branch: Direct dictionary indexing
env[var_name]raisesKeyErrorwhenever a missing variable is actually reached (e.g.,And(Literal(True), Variable("missing"))orNot(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 returnsTrue). - Deeply nested chains (30,000–50,000+ levels): Handled effortlessly in heap memory without hitting Python's
RecursionErrorlimit. - Shared DAG subtrees (same node dict referenced twice): Safe because nodes and
envare read-only and never mutated during traversal.
Common mistakes
- Evaluating both subtrees before applying Python's
and/or: Writingreturn evaluate(left, env) and evaluate(right, env)works in recursion because Python short-circuits the second call, unless you assignright_val = evaluate(right, env)to a variable beforehand — which forcesrightto run unconditionally and triggers falseKeyErrors. - Pushing
leftbeforerightor child before parent on an explicit stack: Because a stack is Last-In, First-Out, pushingleftand thenrightpopsrightfirst! Evaluatingrightbeforeleftbreaks left-to-right short-circuiting onAnd(Variable("active"), Variable("missing_flag")). - Using
env.get(var_name)instead ofenv[var_name]:dict.getreturnsNone(falsy) instead of raisingKeyError, silently turning missing variables intoFalse. - 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_resultandenvto hold eitherboolorintvalues, 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)andleft; stage 1 savesleft_val = last_resultinto(current, 2, left_val)and pushesright; stage 2 verifies that bothleft_valandlast_resultare integers (excludingbool, sinceisinstance(True, int)isTruein Python!) and setslast_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 modifyflag! Copyenvup 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 readingVariable("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 replacingAnd(Literal(False), anything)withLiteral(False)orNot(Not(x))withx(while taking care not to foldAnd(x, Literal(False))intoFalse, becausexcould still raiseKeyError!). 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 (orKeyErroroutcome) 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
- How could we support numeric operands alongside relational nodes such as > or ==?
- What must change if nodes can mutate variable bindings mid-evaluation, like inline assignments?
- How can repeated evaluations of one fixed AST across many distinct variable maps be accelerated?
Similar questions
- Nested Pivot Table Cell Aggregator
- Multi-Column Pivot Table Aggregator
- Pivot Table Class with Cumulative and Summary Totals
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses