Resolve Variable Assignments with Dependencies
Trees & GraphsModel answerLast updated
Parse assignment statements and compute a variable's value by recursively resolving dependencies, detecting cycles and undefined references.
You're given a collection of assignment statements where each statement defines a variable in terms of numeric literals, other variables, or arithmetic operations. Your task is to compute the final numeric value of a specified target variable.
Each assignment has the format name = expression, where:
nameis a valid identifier (letters, digits, underscores; must start with a letter or underscore)expressioncontains integers, decimals, variable names, and the binary operators+and-- Unary minus is allowed (e.g.,
-xor3 - -2) - No parentheses, multiplication, or division
Requirements:
- Compute the numeric value of the target variable by resolving all dependencies
- Detect and report cycles (e.g.,
A = B + 1andB = Awould form a cycle) - Detect and report undefined variable references
- Detect and report duplicate definitions of the same variable
- Handle malformed syntax gracefully with clear error messages
Example:
Given assignments ["X = 10", "Y = X + 5", "Z = Y - X"] and target "Z":
Xevaluates to10Yevaluates to10 + 5 = 15Zevaluates to15 - 10 = 5
Return 5.
What to provide:
- Your approach to modeling and solving this problem
- How you handle cycles and missing variables
- Time and space complexity analysis
- Working code in Python
Hints
Hint 1
Think of assignments as forming a directed graph where edges represent dependencies between variables
Hint 2
Use depth-first search with three states: unvisited, currently visiting (on stack), and fully evaluated
Hint 3
Memoization prevents recomputing shared dependencies and keeps complexity linear
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is fundamentally about dependency resolution in a directed graph. Each variable is a node, and if variable A references variable B in its expression, there's a directed edge from A to B.
Core Strategy
- Parse all assignments into a structured format where each variable maps to its expression decomposed into signed terms
- Build an implicit dependency graph during evaluation
- Use recursive DFS with memoization to compute values on-demand
- Track recursion state to detect cycles using a "visiting" set
Since expressions only contain addition and subtraction (no precedence concerns), we can represent any expression as a linear combination: a list of (sign, type, value) tuples where type is either "number" or "variable".
For example, X - Y + 3 becomes [(+1, var, X), (-1, var, Y), (+1, num, 3)].
Cycle Detection
We maintain three states for each variable:
- Unvisited: not yet evaluated
- Visiting: currently on the DFS call stack (gray node)
- Visited: fully evaluated and memoized (black node)
When we encounter a variable that's already in the "visiting" set, we've found a cycle. This is the standard white-gray-black DFS coloring for cycle detection.
Why This Works
- Correctness: A variable's value is the sum of its signed terms. By recursively evaluating dependencies first, we compute exactly this sum with all variables resolved to numbers.
- Cycle detection: Any cycle reachable from the target must re-enter a node currently on the recursion stack. The "visiting" set catches precisely these back edges.
- Shared dependencies: Diamond patterns (A depends on B and C, both depend on D) are handled correctly because memoization returns cached values for D, and D is no longer in "visiting" when accessed the second time.
Edge Cases to Handle
- Self-loops:
A = A + 1 - Chains of unary operators:
3 - -5should parse as3 - (-5) = 8 - The target variable itself being undefined
- Expressions with only numbers:
X = 42 - Whitespace variations and formatting
- Type preservation: keep integers as integers when possible
Complexity Analysis
Let V be the number of variables and E be the total number of terms across all expressions.
- Time: O(V + E). Each variable is evaluated exactly once due to memoization. Parsing is linear in the input size.
- Space: O(V + E) for storing parsed definitions and memoization cache, plus O(V) for the recursion call stack in worst case (long dependency chain).
Implementation
import re
from typing import Dict, List, Tuple, Union
Number = Union[int, float]
class CycleError(Exception):
pass
class UndefinedVariableError(Exception):
pass
def tokenize_expression(expr: str) -> List[Tuple[str, Union[Number, str]]]:
"""Split expression into tokens: numbers, variables, and operators."""
token_pattern = r'\s*(\d+\.?\d*|\.\d+)|([a-zA-Z_]\w*)|([+-])'
tokens = []
for match in re.finditer(token_pattern, expr):
if match.group(1): # number
num_str = match.group(1)
tokens.append(('num', float(num_str) if '.' in num_str else int(num_str)))
elif match.group(2): # variable
tokens.append(('var', match.group(2)))
else: # operator
tokens.append(('op', match.group(3)))
return tokens
def parse_expression(expr: str) -> List[Tuple[int, str, Union[Number, str]]]:
"""Convert expression into list of (sign, type, value) tuples."""
tokens = tokenize_expression(expr)
if not tokens:
raise ValueError("Empty expression")
terms = []
i = 0
while i < len(tokens):
# Accumulate sign from operators
sign = 1
while i < len(tokens) and tokens[i][0] == 'op':
if tokens[i][1] == '-':
sign *= -1
i += 1
if i >= len(tokens):
raise ValueError("Expression cannot end with operator")
token_type, value = tokens[i]
if token_type not in ('num', 'var'):
raise ValueError(f"Expected number or variable, got {token_type}")
terms.append((sign, token_type, value))
i += 1
# Check for operator between terms
if i < len(tokens) and tokens[i][0] != 'op':
raise ValueError("Missing operator between terms")
return terms
def parse_all_assignments(assignments: List[str]) -> Dict[str, List[Tuple[int, str, Union[Number, str]]]]:
"""Parse all assignment strings into a dictionary."""
definitions = {}
for assignment in assignments:
if '=' not in assignment:
raise ValueError(f"Invalid assignment: {assignment}")
parts = assignment.split('=', 1)
if len(parts) != 2:
raise ValueError(f"Invalid assignment: {assignment}")
var_name = parts[0].strip()
expr = parts[1].strip()
if not re.match(r'^[a-zA-Z_]\w*$', var_name):
raise ValueError(f"Invalid variable name: {var_name}")
if var_name in definitions:
raise ValueError(f"Duplicate definition: {var_name}")
definitions[var_name] = parse_expression(expr)
return definitions
def evaluate_variable(
target: str,
assignments: List[str]
) -> Number:
"""Evaluate target variable by resolving dependencies."""
definitions = parse_all_assignments(assignments)
memo: Dict[str, Number] = {}
visiting = set()
call_stack = []
def resolve(var_name: str) -> Number:
# Already computed
if var_name in memo:
return memo[var_name]
# Check for cycle
if var_name in visiting:
cycle_path = call_stack[call_stack.index(var_name):] + [var_name]
raise CycleError(f"Cycle detected: {' -> '.join(cycle_path)}")
# Check if defined
if var_name not in definitions:
raise UndefinedVariableError(f"Variable '{var_name}' is not defined")
# Mark as visiting
visiting.add(var_name)
call_stack.append(var_name)
# Evaluate the expression
result: Number = 0
for sign, term_type, value in definitions[var_name]:
if term_type == 'num':
result += sign * value
else: # term_type == 'var'
result += sign * resolve(value)
# Mark as complete
visiting.remove(var_name)
call_stack.pop()
memo[var_name] = result
return result
return resolve(target)
# Example usage
assignments = ["X = 10", "Y = X + 5", "Z = Y - X"]
result = evaluate_variable("Z", assignments)
print(f"Z = {result}") # Output: Z = 5
Common Mistakes
- Not handling unary operators correctly:
-X + 5should parse with the minus attached to X, not as a separate operator - Confusing shared dependencies with cycles: A diamond pattern (A→B→D, A→C→D) is not a cycle
- Not memoizing: Without caching, exponential time complexity on shared dependencies
- Forgetting to remove from visiting set: This causes false cycle detection on subsequent evaluations
- Using single visited set: You need both "visiting" (on stack) and "visited" (memoized) states to detect cycles correctly
Follow-up Considerations
- Deep recursion: Very long dependency chains might exceed Python's recursion limit. Consider iterative topological sort.
- Linear equations: Instead of rejecting cycles, you could solve systems like
A = B + 1, B = A + 3using linear algebra (has unique solution: A=B+1 and B=A+3 implies A=A+4, no solution). - Operator precedence: If multiplication/division were added, you'd need proper expression parsing with precedence rules.
- Parallelization: Independent branches of the dependency graph could be evaluated concurrently.