Resolve Boolean Signal Chains with Negation and Cycle Detection
Trees & GraphsAuto-graded · 19 test casesLast updated
Tests iterative functional-graph traversal: propagating True/False through chains of references and NOT, while correctly marking cycles, dangling references, and their dependents as unresolvable.
Problem
You are building a signal propagation system for a hardware simulator. Each signal has a unique string name and is defined by exactly one of the following expressions:
"TRUE"— the signal is always on"FALSE"— the signal is always off"<name>"— the signal copies the value of the named signal"NOT <name>"— the signal is the logical inverse of the named signal
Signals may form long dependency chains spanning multiple disconnected groups. A signal cannot be resolved if any of the following apply:
- It depends on a name that does not appear in the signal table (undefined reference).
- It is part of a dependency cycle (e.g.,
Pdepends onQandQdepends onP). - It depends on another signal that itself cannot be resolved.
Write a function evaluate_signals that accepts the signal table and returns the resolved value of every signal.
Input
signal_table: a dictionary mapping each signal name (str) to its expression (str).- Every expression is one of:
"TRUE","FALSE", a bare name, or"NOT <name>".
- Every expression is one of:
Output
A dictionary mapping every key in signal_table to True, False, or None (unresolvable).
Constraints
1 <= len(signal_table) <= 10^5- Signal names consist of alphanumeric characters and underscores only.
- Your solution must run in
O(V + E)time, whereVis the number of signals. Because each signal has at most one dependency,E <= V. - Do not use recursion; the chain length can reach
10^5. - A signal that directly references itself is a cycle and resolves to
None. - Only keys present in
signal_tableappear in the output; undefined names are never added.
Examples
Example 1
Input: evaluate_signals({'A': 'NOT B', 'B': 'C', 'C': 'TRUE', 'D': 'NOT C'})
Output: {'A': False, 'B': True, 'C': True, 'D': False}
Example 2
Input: evaluate_signals({'X': 'NOT Y', 'Y': 'X', 'Z': 'Y', 'W': 'TRUE'})
Output: {'X': None, 'Y': None, 'Z': None, 'W': True}
Example 3
Input: evaluate_signals({'A': 'B', 'B': 'NOT MISSING_VAR'})
Output: {'A': None, 'B': None}
Hints
Hint 1
Each signal has at most one outgoing dependency edge, so the graph is a collection of simple chains that may end in a literal, a cycle, or an undefined name — no branching needed.
Hint 2
Walk each chain forward, recording visited nodes in order. Once you find a terminal condition (literal, undefined, cycle, or already-resolved node), sweep back through the recorded path to assign values — flipping the boolean at each NOT node.
Hint 3
Use three states per node — unseen, currently on the active path, and finished — to tell the difference between a real cycle (you reach a node still on the current path) and a node whose value is already known from a previous walk.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key structural observation
Every signal depends on at most one other signal. That means the dependency graph is a functional graph: a collection of simple chains, each of which terminates in exactly one of four ways:
- A literal (
TRUE/FALSE) — the chain is fully resolvable. - An undefined name — the chain cannot be resolved.
- A node that is already finished from an earlier walk — reuse its cached value.
- A node that is currently on the path being walked — this is a cycle.
No branching ever occurs, so a depth-first search with a stack is unnecessary. A simple forward walk along the chain is enough.
Algorithm
Parse first. Scan each expression once and record three things per signal: its literal value if it is TRUE/FALSE (otherwise None), its dependency name (or None for literals), and a boolean flag for whether it is a NOT reference.
Three-state coloring. Assign each signal one of three states:
0unseen1active — currently on the path being walked2finished — final value is known
Walk and back-propagate. For each unfinished signal, walk forward through the dependency chain, appending each newly visited node to a path list and marking it active. Stop when reaching a terminal condition, then sweep path in reverse:
- If the walk ended on a cycle or an unresolvable base, every node on
pathgetsNone. - Otherwise, start with the base boolean and work backwards: copy it at direct-reference nodes and flip it at
NOTnodes.
Why it is correct
- Cycles: A node is detected as part of a cycle when the walk arrives at a node already in state
1. Every node inpathat that point either sits on the cycle or flows into it — either way it is unresolvable. - Undefined references: The walk exits the loop with no valid base, so the entire path becomes
None. - Cascading
None: A finished node with valueNoneacts as a base ofNone, which propagates back through the new path. - Negation parity: Sweeping backwards and flipping at each
NOTnode correctly handles arbitrarily long chains of negation, including double negation. - Each node is processed once: A node moves from state
0to1to2exactly once, so no value is computed more than once.
Complexity
- Time: O(V) — each node is appended to a path and finalized once; each dependency edge is followed at most once.
- Space: O(V) — for the state, value, parsed metadata, and the path list.
Edge cases
- Self-loop (
"A": "A"):Abecomes active, the walk immediately sees it in state1, and it getsNone. - Chain into a prior failure (
"A": "B"whereBis alreadyNone): the finishedNonebase propagates toA. - Deep chains (10^5 nodes): the algorithm is fully iterative, so Python's recursion limit is never hit.
- Disconnected components: the outer loop over all signals ensures every component is visited.
Reference solution
from typing import Optional
def evaluate_signals(signal_table: dict[str, str]) -> dict[str, Optional[bool]]:
# --- parse each expression once ---
lit: dict[str, Optional[bool]] = {} # non-None only for TRUE/FALSE nodes
dep: dict[str, Optional[str]] = {} # the single dependency name, or None
neg: dict[str, bool] = {} # True when expression is "NOT <name>"
for name, expr in signal_table.items():
if expr == "TRUE":
lit[name], dep[name], neg[name] = True, None, False
elif expr == "FALSE":
lit[name], dep[name], neg[name] = False, None, False
elif expr.startswith("NOT "):
lit[name], dep[name], neg[name] = None, expr[4:], True
else:
lit[name], dep[name], neg[name] = None, expr, False
# --- three-colour iterative walk ---
# 0 = unseen, 1 = active (on current path), 2 = finished
state: dict[str, int] = {n: 0 for n in signal_table}
value: dict[str, Optional[bool]] = {n: None for n in signal_table}
for start in signal_table:
if state[start] == 2:
continue
path: list[str] = []
node = start
base_value: Optional[bool] = None
resolved_base = False
cycle = False
# walk forward until we hit a terminal condition
while True:
if node not in signal_table:
# undefined reference — whole path is unresolvable
break
if state[node] == 0:
if lit[node] is not None:
# literal node: resolve it immediately, use as base
state[node] = 2
value[node] = lit[node]
base_value = lit[node]
resolved_base = True
break
# unseen non-literal: add to path and continue
state[node] = 1
path.append(node)
node = dep[node] # type: ignore[assignment]
elif state[node] == 1:
# reached a node still on the current path → cycle
cycle = True
break
else:
# state == 2: already resolved in a prior walk
base_value = value[node]
resolved_base = (base_value is not None)
break
# propagate result back along the recorded path
if cycle or not resolved_base:
for name in path:
state[name] = 2
value[name] = None
else:
current: Optional[bool] = base_value
for name in reversed(path):
if neg[name]:
current = not current
value[name] = current
state[name] = 2
return {name: value[name] for name in signal_table}