Evaluate Variable Expressions with Dependencies
Trees & GraphsAuto-graded · 19 test casesLast updated
Evaluate symbolic variable definitions with standard arithmetic precedence, resolving variable dependencies while detecting cycles and missing definitions.
You are given a dictionary expressions where each key is a variable identifier and each value is an arithmetic expression string.
An expression string consists of:
- Non-negative integer literals (e.g.,
"42") - Variable identifiers referencing other keys in
expressions - Binary operators:
+,-, and* - Single space delimiters between tokens
Your task is to calculate and return a dictionary mapping every variable to its fully evaluated integer value.
Processing Rules
- Operator Precedence: Operators follow standard math precedence (
*evaluates before+and-). Operators of identical precedence evaluate left-to-right. - Dependency Resolution: A variable can reference other variables in its expression. Each variable must be evaluated after all variables it depends on have been calculated.
- Validation & Errors:
- If an expression references a variable identifier that does not exist in
expressions, raise aValueErrorwith the message:"Undefined variable: <name>"(where<name>is the name of the missing variable). - If a circular dependency exists among the variable definitions (e.g.,
xreferencesyandyreferencesx), raise aValueErrorwith the exact message:"Circular dependency detected".
- If an expression references a variable identifier that does not exist in
Constraints
1 <= len(expressions) <= 10^4- Variable identifiers consist of letters, digits, and underscores.
- Each expression string contains between 1 and 200 characters.
- Operands and operators are strictly separated by single spaces.
- Intermediate and final values fit within standard signed 64-bit integers.
Examples
Example 1
Input: evaluate_expressions({'A': '3 + 2', 'B': 'A * 4', 'C': 'B - 2 + A'})
Output: {'A': 5, 'B': 20, 'C': 23}
Hints
Hint 1
Model the variables as nodes in a graph where directed edges point from a variable to its referenced dependencies.
Hint 2
Use a 3-state graph traversal (Unvisited, Visiting, Visited) to perform topological sorting and detect cycles along the path.
Hint 3
Because expressions lack parentheses, you can compute them in a single linear scan maintaining a running total and a current term for multiplication precedence.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem involves two main tasks:
-
Dependency Order & Cycle Detection: Variables form a directed graph where an edge goes from a variable to any variable it relies upon. We need to evaluate dependent variables before the variables that reference them. A 3-state Depth-First Search (DFS) or post-order traversal works well here:
0(Unvisited): Node has not been encountered yet.1(Visiting): Node is currently on the traversal stack. Encounteing a node in this state means a cycle exists.2(Visited/Evaluated): Node and all its sub-dependencies are completely calculated and stored.
-
Expression Evaluation: Since token strings are space-separated and do not contain parentheses, we can evaluate each expression in $O(N)$ time with standard arithmetic precedence (
*before+/-). We maintain:total: Running sum of fully resolved additive terms.term: The current multiplicative block.sign: The sign (+1or-1) for the next additive term.
When encountering
*, we updateterm *= next_operand. When encountering+or-, we accumulatesign * termintototal, set the newsign, and resettermtonext_operand.
To handle potentially deep dependency chains without exceeding Python's default recursion limit, we can implement the post-order DFS iteratively using an explicit stack.
Complexity
- Time Complexity: $O(V + T)$ where $V$ is the number of variables and $T$ is the total number of tokens across all expressions. Each variable and dependency edge is processed a constant number of times.
- Space Complexity: $O(V + T)$ to store split tokens, traversal state markers, memoized computed values, and the DFS call stack.
Python Reference Solution
def evaluate_expressions(expressions: dict[str, str]) -> dict[str, int]:
state = {} # 0: UNVISITED (default), 1: VISITING, 2: VISITED
values = {}
tokens_by_name = {name: expr.split() for name, expr in expressions.items()}
dependencies = {}
# Extract all non-operator, non-literal tokens as dependencies
for name, tokens in tokens_by_name.items():
dependencies[name] = [
token for token in tokens
if token not in ("+", "-", "*") and not token.isdigit()
]
for root in expressions:
if state.get(root) == 2:
continue
state[root] = 1
stack = [[root, 0]]
while stack:
name, index = stack[-1]
deps = dependencies[name]
# If there are unresolved dependencies for the current node
if index < len(deps):
dep = deps[index]
stack[-1][1] += 1
if dep not in expressions:
raise ValueError(f"Undefined variable: {dep}")
dep_state = state.get(dep, 0)
if dep_state == 1:
raise ValueError("Circular dependency detected")
if dep_state == 0:
state[dep] = 1
stack.append([dep, 0])
continue
# All dependencies are computed; now evaluate the expression
tokens = tokens_by_name[name]
position = 0
def operand():
nonlocal position
token = tokens[position]
position += 1
return int(token) if token.isdigit() else values[token]
total = 0
sign = 1
term = operand()
while position < len(tokens):
operator = tokens[position]
position += 1
value = operand()
if operator == "*":
term *= value
else:
total += sign * term
sign = 1 if operator == "+" else -1
term = value
values[name] = total + sign * term
state[name] = 2
stack.pop()
return {name: values[name] for name in expressions}