Resolve Variable Dependencies with Arithmetic
Trees & GraphsAuto-graded · 23 test casesLast updated
Tests dependency graph traversal, cycle detection, and recursive evaluation of variables defined by arithmetic expressions.
You are given a target variable name and a list of variable assignments. Each assignment defines a variable in terms of:
- An integer literal (e.g.,
"X=5"), - Another variable (e.g.,
"X=Y"), or - An arithmetic expression with exactly one
+or-operator between two operands (e.g.,"X=Y+Z"or"X=A-B"), where each operand is either an integer literal or a variable name.
Your task is to compute the numeric value of the target variable by resolving all dependencies.
If the dependency graph contains a cycle (a variable's value depends on itself, directly or indirectly), or if any required variable is undefined, return the string "IMPOSSIBLE".
Details:
- Variable names and integer literals may contain negative signs. A leading
-in an expression like"X=-5"represents a negative literal, not an operator. - Operators (
+or-) appear at position 1 or later in the right-hand side, so"X=-3"is interpreted as assigning-3toX, not asX = (nothing) - 3. - Whitespace in assignments may be present and should be ignored.
- If a variable is assigned multiple times, use the last assignment.
Constraints:
- 1 ≤ number of assignments ≤ 1000
- Variable names are non-empty strings
- Integer values fit within standard 32-bit signed integer range
- Each arithmetic expression contains at most one operator
- The target variable is a non-empty string
Examples
Example 1
Input: resolve_variable('T3', ['T1=1', 'T2=2', 'T3=T4', 'T4=T5', 'T5=T2'])
Output: 2
Example 2
Input: resolve_variable('T3', ['T1=7', 'T2=4', 'T3=T1+T2'])
Output: 11
Example 3
Input: resolve_variable('T4', ['T4=T5', 'T5=T4'])
Output: 'IMPOSSIBLE'
Hints
Hint 1
Model the assignments as a directed graph where each variable points to the variables it depends on.
Hint 2
Use depth-first search with three states (unvisited, visiting, visited) to detect cycles during traversal.
Hint 3
Parse each right-hand side by scanning for the first + or - operator starting from index 1 to handle negative literals correctly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the variable assignments as a directed dependency graph. Each variable points to the variables appearing in its definition. To compute the target variable's value, perform a depth-first search through this graph, recursively evaluating dependencies.
Use a three-state tracking system for cycle detection:
- Unvisited (not in the state map)
- Visiting (state = 1, currently being evaluated in the recursion stack)
- Visited (state = 2, value already computed and cached)
If we encounter a variable that is currently being visited, a cycle exists and evaluation is impossible.
For parsing, scan each right-hand side starting from index 1 (not 0) to find the first + or - operator. Starting at index 1 allows a leading minus sign to be treated as part of a negative integer literal rather than an operator. If no operator is found, the expression is either an integer literal or a single variable reference.
Correctness
The algorithm correctly handles:
- Cycles: Any variable that depends on itself (directly or through a chain) is detected when we revisit a node in state 1.
- Memoization: Once a variable's value is computed, it's cached (state 2) so subsequent references return immediately without re-evaluation.
- Undefined variables: If a variable is referenced but has no assignment, we catch the KeyError and return "IMPOSSIBLE".
- Arithmetic: Each operator is applied after recursively resolving both operands.
Complexity
Time: O(V + E) where V is the number of unique variables and E is the total number of variable references in all expressions. Each variable is evaluated at most once due to memoization, and we visit each dependency edge once.
Space: O(V) for the definitions map, state tracking, memoization, and the recursion call stack in the worst case (a long chain of dependencies).
Solution
from typing import List
def resolve_variable(target: str, assignments: List[str]) -> object:
definitions = {}
for assignment in assignments:
var_name, expr = assignment.replace(" ", "").split("=", 1)
definitions[var_name] = expr
node_state = {}
computed = {}
def evaluate(var):
if var not in definitions:
raise KeyError(var)
if node_state.get(var) == 1:
raise ValueError("cycle detected")
if node_state.get(var) == 2:
return computed[var]
node_state[var] = 1
expr = definitions[var]
op = None
op_pos = -1
for idx in range(1, len(expr)):
if expr[idx] in "+-":
op = expr[idx]
op_pos = idx
break
if op is None:
try:
result = int(expr)
except ValueError:
result = evaluate(expr)
else:
left_part = expr[:op_pos]
right_part = expr[op_pos + 1:]
left_val = int(left_part) if left_part.lstrip("-").isdigit() else evaluate(left_part)
right_val = int(right_part) if right_part.lstrip("-").isdigit() else evaluate(right_part)
result = left_val + right_val if op == "+" else left_val - right_val
node_state[var] = 2
computed[var] = result
return result
try:
return evaluate(target)
except (KeyError, ValueError):
return "IMPOSSIBLE"