Resolve Variables from Linked Assignment Rules with Cycle Checks
Trees & GraphsModel answerLast updated
Evaluate a target variable from a list of assignment strings, growing from simple aliasing to signed sums of variables and integers, then detect circular dependencies safely.
You are given a list of assignment strings and the name of a target variable. Compute the integer value of the target.
Example: with target T1 and the assignments
T1 = T2
T2 = 5
the result is 5, because T1 refers to T2, which holds 5.
The task is built up in three stages. Design your solution so that each stage extends the previous one.
Stage 1: Alias chains
The right-hand side of every assignment is either an integer literal or the name of exactly one other variable. Return the target's value by following the chain of references.
Discuss and handle:
- How you store the assignments for fast lookup.
- How you avoid resolving the same variable repeatedly.
- What happens when the target or a variable it relies on is never assigned.
- What happens when the same variable is assigned more than once.
Stage 2: Sums and differences
The right-hand side may now be an expression made from variable names and integers joined by + and -.
T1 = T2 + 3 - T3
T2 = 5
T3 = T2 - 1
Here T3 = 4, so T1 = 5 + 3 - 4 = 4.
Requirements:
- Whitespace is optional, so
T2+3is valid. - Malformed expressions such as
T2 3orT2 +must be rejected with a clear error. - Decide and state your rule for a leading sign (
T1 = -T2) and for consecutive operators. - A variable used by several other variables must not be recomputed each time.
State the time complexity in terms of the number of variables and the total length of all expressions.
Stage 3: Circular definitions
The input may now contain cycles:
A = B + 1
B = C
C = A - 2
Instead of recursing forever, detect the cycle and report an error.
Discuss and handle:
- Telling a genuine cycle apart from a variable that is merely reached twice through different routes (a shared dependency is not a cycle).
- Whether you reject the whole input or only fail when the target actually depends on the cycle.
- Whether the error names the variables on the cycle.
- Behavior on very long chains, where deep recursion could overflow the stack.
Provide the code, its complexity, and the test cases you would run for each stage.
Hints
Hint 1
Parse every line once into a dictionary from variable name to a list of signed terms (each term is either an integer or a variable name with a sign). Stage 1 is just the special case of a single positive term.
Hint 2
Use three states per variable during DFS: unvisited, in progress, done. Reaching an in-progress variable means a real cycle; reaching a done variable simply reuses its cached value, which is why diamonds are not flagged.
Hint 3
To report the cycle and avoid recursion limits, keep an explicit path stack. When you hit an in-progress variable, slice the path from its first occurrence to get the cycle members. An iterative DFS with a stack of (variable, term index) frames removes the depth limit.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each variable as a node in a dependency graph. An assignment X = a + b - c gives edges from X to each variable on its right-hand side. Evaluating the target is a depth-first traversal that computes values in post-order, caching each result.
Parsing
- Split each line on the first
=. The left side must be a valid identifier (for example[A-Za-z_][A-Za-z0-9_]*); otherwise raise an error. - Tokenize the right side with a regular expression such as
\s*([+-]|\d+|[A-Za-z_]\w*)\s*, and verify that the whole string was consumed. This handlesT2+3and rejects stray characters. - Enforce the grammar:
[sign] operand (sign operand)*. Operands and operators must strictly alternate, soT2 3(two operands) andT2 +(dangling operator) both fail. My chosen rule: a single leading+or-is allowed (-T2), but two operators in a row (T2 + - 3) are rejected. Whatever you pick, say it out loud and test it. - Store the result as
rules[name] = [(sign, operand), ...], where an operand is an int or a variable name. - Duplicate assignment: I would raise an error, since silent "last wins" hides data bugs. If the spec said otherwise, document it.
Evaluation with memoization and cycle detection
Use three states: unvisited, visiting, done.
import re
TOKEN = re.compile(r"\s*([+-]|\d+|[A-Za-z_]\w*)\s*")
def tokenize(s):
pos, out = 0, []
s = s.strip()
while pos < len(s):
m = TOKEN.match(s, pos)
if not m:
raise ValueError(f"bad character in {s!r}")
out.append(m.group(1))
pos = m.end()
return out
def parse_rhs(tokens):
terms, sign, expect_operand = [], 1, True
i = 0
if tokens and tokens[0] in "+-":
sign = 1 if tokens[0] == "+" else -1
i = 1
while i < len(tokens):
t = tokens[i]
if expect_operand:
if t in "+-":
raise ValueError("unexpected operator")
terms.append((sign, int(t) if t.isdigit() else t))
expect_operand = False
else:
if t not in "+-":
raise ValueError("missing operator")
sign = 1 if t == "+" else -1
expect_operand = True
i += 1
if expect_operand:
raise ValueError("expression is empty or ends with an operator")
return terms
def parse(lines):
rules = {}
for line in lines:
if line.count("=") != 1:
raise ValueError(f"bad line {line!r}")
lhs, rhs = line.split("=")
lhs = lhs.strip()
if not re.fullmatch(r"[A-Za-z_]\w*", lhs):
raise ValueError(f"bad name {lhs!r}")
if lhs in rules:
raise ValueError(f"duplicate assignment to {lhs}")
rules[lhs] = parse_rhs(tokenize(rhs))
return rules
def evaluate(lines, target):
rules = parse(lines)
if target not in rules:
raise KeyError(f"{target} is undefined")
value, state, path = {}, {}, [] # state: 1 = visiting, 2 = done
# iterative DFS: frame = [name, next term index, running total]
stack = [[target, 0, 0]]
state[target] = 1
path.append(target)
while stack:
frame = stack[-1]
name, idx, _ = frame
terms = rules[name]
if idx == len(terms):
value[name] = frame[2]
state[name] = 2
path.pop()
stack.pop()
if stack:
parent = stack[-1]
sign, _ = rules[parent[0]][parent[1]]
parent[2] += sign * value[name]
parent[1] += 1
continue
sign, op = terms[idx]
if isinstance(op, int):
frame[2] += sign * op
frame[1] += 1
elif op not in rules:
raise KeyError(f"{op} is undefined (needed by {name})")
elif state.get(op) == 2:
frame[2] += sign * value[op]
frame[1] += 1
elif state.get(op) == 1:
cyc = path[path.index(op):] + [op]
raise ValueError("cycle: " + " -> ".join(cyc))
else:
state[op] = 1
path.append(op)
stack.append([op, 0, 0])
return value[target]
Why shared dependencies are not flagged
In T1 = T2 + T3, T3 = T2 - 1, T2 = 5, the variable T2 is reached twice. The first visit finishes and is marked done. The second visit sees "done" and reuses the cached value. Only meeting a variable in the "visiting" state, meaning it is still on the current path, proves a cycle. A simple "seen before" set would produce false positives here, which is the most common mistake.
Scope of the cycle check
I only traverse what the target depends on, so a cycle elsewhere in the input does not affect the answer. This is the least surprising behavior for a query-style API. If the product requirement is to validate the whole configuration, run the same DFS from every unvisited variable (or Kahn's algorithm on the whole graph) before answering queries. Mention this trade-off explicitly.
The error message lists the path slice from the first occurrence of the repeated variable, for example A -> B -> C -> A, which makes the bad input easy to fix. A self-reference such as A = A + 1 is reported as A -> A.
Complexity
- Parsing: O(L), where L is the total length of all lines.
- Evaluation: each variable is expanded once and each term is consumed once, so O(V + T) where T is the total number of terms (bounded by L).
- Space: O(V + T) for rules, cache, and stack.
Recursion depth
A recursive DFS on a chain of 100,000 assignments overflows Python's default stack. The iterative version above uses an explicit stack, so depth is limited only by memory. Alternatives are raising the recursion limit (fragile) or a topological order via Kahn's algorithm on the reachable subgraph.
Tests to run
- Stage 1: simple chain; literal target; undefined target; undefined dependency in the middle of a chain; duplicate assignment.
- Stage 2: the
T1 = T2 + 3 - T3example (expect 4); no whitespace (T2+3); leading sign; negative results; malformedT2 3,T2 +,T2 + - 3, empty right-hand side. - Shared dependency (diamond): must return a value, not a cycle error.
- Stage 3: three-node cycle; self-reference; cycle not reachable from the target (should succeed); cycle reachable through one branch only (should fail and name the cycle).
- A 100,000-long chain to confirm no stack overflow.
Common mistakes
- Using a global "visited" set as the cycle test, which flags diamonds.
- Forgetting to apply the sign of a term to a variable's value rather than only to literals.
- Tokenizing with
split()and so failing onT2+3. - Silently treating an undefined variable as zero.
- Relying on recursion for deep inputs.