Evaluate Chained Sum Definitions with Error Detection
Trees & GraphsModel answerLast updated
Compute the integer value of every variable defined as a sum of literals and other variables, raising distinct errors for duplicate, undefined, or circular definitions.
Resolve a Set of Sum Definitions
A simulation tool stores its settings as a list of text definitions. Each definition gives one name a value written as a sum of one or more terms joined by +. A term is either:
- a signed 64-bit integer literal such as
5or-12, or - a variable name made of letters, digits, and underscores (case-sensitive).
Write evaluate_equations so that it computes the final integer value of every defined name and returns a dictionary from name to value.
Raise the matching custom exception when the input is invalid:
UndefinedVariableError: a right-hand side uses a name that is never defined on the left of any line.CycleError: names depend on each other in a loop (for exampleA = B + 1together withB = A).DuplicateDefinitionError: the same name is defined on the left of more than one line.
class UndefinedVariableError(Exception):
pass
class CycleError(Exception):
pass
class DuplicateDefinitionError(Exception):
pass
def evaluate_equations(equations: list[str]) -> dict[str, int]:
...
Input
equations: a list of strings, each shaped likename = term + term + ... + term. Tokens are separated by whitespace.
Constraints
1 <= len(equations) <= 20,000- The total number of terms over all lines is at most
100,000. - Every literal lies in
[-2^63, 2^63 - 1]. - The solution must run in
O(V + E)time, whereVis the number of distinct names andEthe number of name references.
Examples
evaluate_equations([
"speed = base_speed + offset",
"base_speed = 30",
"offset = 5 + 3",
"max_speed = speed + 10",
])
# {"speed": 38, "base_speed": 30, "offset": 8, "max_speed": 48}
evaluate_equations(["x = y + 2", "y = z + 1", "z = x + 4"])
# raises CycleError
evaluate_equations(["foo = bar + 10"])
# raises UndefinedVariableError
What to cover in your answer
Explain your approach, state how you order the errors when several apply at once, discuss edge cases, give the complexity, and provide working code.
Hints
Hint 1
Split each line into a constant part (the sum of its literals) and a list of referenced names. Keep repeated references, since `a = b + b` uses `b` twice.
Hint 2
Treat names as graph nodes with an edge from each dependency to the name that uses it. A name can be computed once all of its references are computed, which is exactly what topological ordering gives you.
Hint 3
Run Kahn's algorithm with in-degree equal to the number of references (with multiplicity). If fewer nodes are processed than were defined, a cycle exists. Check duplicates and undefined names before evaluating, and decide on an error priority.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is evaluation over a dependency graph. Each line v = t1 + t2 + ... splits into:
- a constant: the sum of all integer literals on the right, and
- a reference list: the names on the right, kept with repetition.
The value of v is its constant plus the values of its references. That is well defined only when the graph has no cycle, so the task becomes a topological evaluation with validation.
Phases
- Parse. Split each line at the first
=. Strip the left side to get the target name. If the target was already seen, raiseDuplicateDefinitionError. Split the right side on+, and classify each term as an integer literal (regex-?\d+) or a name ([A-Za-z0-9_]+). Avoid a bareint()for classification because it also accepts forms like+5and1_000. - Validate references. Any referenced name missing from the defined set raises
UndefinedVariableError. After this step, every edge points at a node that has an equation. - Evaluate with Kahn's algorithm.
- Edge direction: dependency to dependent.
indegree[v]is the number of references inv's line, with multiplicity.- Start the queue with names whose in-degree is 0 (only literals).
- When
uis popped, addvalue[u]into each dependent once per occurrence, decrement its in-degree, and enqueue it when it reaches 0. - If the number of processed names is below the number of defined names, the rest lie on or behind a cycle, so raise
CycleError.
Why Kahn instead of recursive DFS
Kahn's algorithm is iterative, so a chain of 50,000 names cannot hit Python's recursion limit, and it evaluates and detects cycles in a single pass. A DFS is fine only with an explicit stack and three-color marking. Raising sys.setrecursionlimit is fragile because the C stack can still overflow.
Error precedence
The task does not say which error wins when several are present. A deterministic choice is Duplicate, then Undefined, then Cycle. Duplicates appear during parsing, undefined names are found before building the graph, and cycles only show up during evaluation. State this choice explicitly.
Correctness
- A name is enqueued only after all its references are fully resolved, so its accumulated value is exactly constant plus the sum of its dependencies' values.
- Repeated references such as
b + bare handled becausedependents[b]contains the name twice, sovalue[b]is added twice and the in-degree is 2. - In an acyclic graph every node is eventually processed. On a cycle, no node can reach in-degree 0, nor can anything that depends on it, so the processed count falls short exactly when a cycle exists. A self-reference like
a = a + 1is a cycle of length 1 and is caught the same way.
Complexity
- Time:
O(V + E + T), whereTis the total token count. WithT <= 100,000this is linear. - Space:
O(V + E)for the constants, adjacency lists, in-degrees, and values.
Edge cases
- Negative literals (
x = -12 + y) must be recognized as literals. - Repeated references (
a = b + b) count twice. - Self-loop (
a = a) raisesCycleError. - An input with both an undefined name and a cycle raises
UndefinedVariableErrorunder the stated precedence. - Python integers are unbounded, so sums of 64-bit literals are exact. In C++ or Java you would have to choose between wraparound and an explicit overflow error.
- Malformed lines (no
=, empty term) are outside the three custom errors, so raiseValueError. - Return the dictionary in equation order, which matches Example 1.
Code
import re
from collections import deque
class UndefinedVariableError(Exception):
pass
class CycleError(Exception):
pass
class DuplicateDefinitionError(Exception):
pass
_INT_RE = re.compile(r"-?\d+")
_NAME_RE = re.compile(r"[A-Za-z0-9_]+")
def evaluate_equations(equations: list[str]) -> dict[str, int]:
constant: dict[str, int] = {}
refs: dict[str, list[str]] = {}
# 1. Parse and detect duplicates
for eq in equations:
if "=" not in eq:
raise ValueError(f"Malformed equation: {eq!r}")
lhs, rhs = eq.split("=", 1)
target = lhs.strip()
if not _NAME_RE.fullmatch(target):
raise ValueError(f"Invalid target in: {eq!r}")
if target in constant:
raise DuplicateDefinitionError(target)
total, deps = 0, []
for term in rhs.split("+"):
term = term.strip()
if _INT_RE.fullmatch(term):
total += int(term)
elif _NAME_RE.fullmatch(term):
deps.append(term)
else:
raise ValueError(f"Invalid term {term!r} in: {eq!r}")
constant[target] = total
refs[target] = deps
# 2. Check references
for deps in refs.values():
for d in deps:
if d not in constant:
raise UndefinedVariableError(d)
# 3. Kahn's algorithm
indegree = {v: len(deps) for v, deps in refs.items()}
dependents = {v: [] for v in refs}
for v, deps in refs.items():
for d in deps:
dependents[d].append(v)
value = dict(constant)
queue = deque(v for v, k in indegree.items() if k == 0)
processed = 0
while queue:
u = queue.popleft()
processed += 1
for v in dependents[u]:
value[v] += value[u]
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
if processed != len(constant):
stuck = [v for v, k in indegree.items() if k > 0]
raise CycleError(f"Circular dependency among: {stuck}")
return {v: value[v] for v in refs}
Trace of Example 1. base_speed (30) and offset (8) start with in-degree 0. Popping them adds 30 and 8 to speed, giving 38. speed then reaches in-degree 0 and adds 38 to max_speed, giving 48.
Common mistakes
- Deduplicating references, which breaks
a = b + b. - Using recursion and failing on long chains.
- Using
int()to decide whether a term is a literal. - Checking for cycles before undefined names, so the graph has dangling edges.
- Leaving the error order unspecified.
Follow-ups
- Deep chains: already handled, since Kahn's algorithm uses no recursion.
- Updating a single equation at runtime: keep the reverse graph, and on a change re-evaluate only the affected names in topological order, rejecting the update if it would introduce a cycle.