Process Sequential Variable Assignments
StringsAuto-graded · 18 test casesLast updated
Tests parsing and evaluating variable assignments in order, handling literals, references, and arithmetic expressions.
You are given a sequence of variable assignments and a target variable name. Each assignment defines a variable as either a number, a reference to a previously defined variable, or an arithmetic expression using addition and subtraction.
Process the assignments in order and return the final value of the target variable.
Input Format
assignments: A list of strings, each containing one assignment in the formatname = expressiontarget: The name of the variable whose value you need to return
Assignment Rules
Each assignment follows the pattern name = expression, where:
- The left side is a variable name (lowercase letters followed by zero or more lowercase letters or digits)
- The right side is an expression containing:
- Unsigned decimal integers
- Variable names (referring only to variables defined earlier in the list)
- The operators
+and- - Optional spaces around tokens
Expressions are evaluated left to right. For example, a - b + c means (a - b) + c.
Guarantees
- Each variable is defined exactly once
- Variables can only reference other variables that appear earlier in the list
- No cycles or forward references exist
- The target variable will be defined in the list
- All intermediate and final values fit within a signed 32-bit integer
- Results may be negative
Constraints
- 1 ≤ len(assignments) ≤ 10,000
- Total input length ≤ 200,000 characters
- Variable names match the pattern
[a-z][a-z0-9]* - Integer literals are non-negative and match
[0-9]+ - No unary operators, parentheses, multiplication, or division
Examples
Example 1
Input: process_assignments(['x1=1', 'x2=x1', 'x3=x2+x1', 'x4=x3-5'], 'x4')
Output: -3
Example 2
Input: process_assignments(['a=8', 'b=a', 'c=a', 'd=b-c'], 'd')
Output: 0
Hints
Hint 1
Store computed values in a dictionary as you process each assignment in order
Hint 2
Use a regular expression to tokenize the right-hand side into variable names, numbers, and operators
Hint 3
Evaluate expressions left to right using an accumulator and the last-seen operator
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires processing variable assignments sequentially, maintaining computed values in a lookup structure. Since each variable is defined exactly once and can only reference earlier variables, a single left-to-right pass through the assignments is sufficient.
The algorithm follows these steps for each assignment:
- Parse the assignment: Split on the first
=to separate the variable name from its expression - Tokenize the expression: Extract variable names, numeric literals, and operators using a regular expression
- Evaluate left to right: Use an accumulator that starts with the first term, then apply each operator to the next term in sequence
- Store the result: Save the computed value in a dictionary keyed by the variable name
After processing all assignments, look up and return the target variable's value.
Why It Works
The correctness follows from the guarantee that variables only reference earlier definitions. By the time we evaluate any expression, all variables it references have already been computed and stored.
The left-to-right evaluation matches the specified semantics: a - b + c is interpreted as (a - b) + c. We maintain a pending operator (initially +) and apply it when we encounter each new term.
Since each variable is assigned exactly once, the dictionary gives us a consistent snapshot of all definitions at any point.
Complexity
- Time: O(L) where L is the total length of all assignment strings. Splitting, tokenizing with regex, and evaluating each expression are all linear in their input size. Dictionary operations are O(1) expected time.
- Space: O(V) where V is the number of variables, to store the symbol table. Token lists are processed one at a time.
Implementation
import re
from typing import List
def process_assignments(assignments: List[str], target: str) -> int:
symbol_table = {}
token_regex = re.compile(r"[a-z][a-z0-9]*|[0-9]+|[+-]")
for assignment in assignments:
var_name, expr = assignment.split("=", 1)
var_name = var_name.strip()
tokens = token_regex.findall(expr)
result = None
pending_op = "+"
for token in tokens:
if token in ("+", "-"):
pending_op = token
continue
term = int(token) if token[0].isdigit() else symbol_table[token]
if result is None:
result = term
elif pending_op == "+":
result += term
else:
result -= term
symbol_table[var_name] = result
return symbol_table[target]