Resolve Out-of-Order Variable Assignments in a Mini Language
Trees & GraphsModel answerLast updated
Parse lines of integer assignments using only + and -, resolve forward and chained references, and report undefined names and cycles in a well-defined way.
Problem
You are given the source of a tiny scripting language. Each non-empty line is a single assignment:
<name> = <expression>
<name>matches[a-zA-Z_][a-zA-Z0-9_]*.<expression>is a chain of non-negative integer literals and variable names joined by+and-.- There are no parentheses, and operators are applied strictly left to right.
- Whitespace may appear anywhere, or nowhere, and carries no meaning.
foo=bar+5-bazandfoo = bar + 5 - bazare the same statement. - All values are integers.
A variable may refer to variables assigned earlier or later in the text, and references can form long chains (a uses b, b uses c, and so on).
Task
Implement:
evaluate(program: string) -> Map<string, int>
It returns the final integer value of every variable in the program.
Examples
foo = bar + 5
bar = 2
gives { "bar": 2, "foo": 7 }.
foo = bar + 1
bar = baz + 1
baz = 3
gives { "baz": 3, "bar": 4, "foo": 5 }.
Error situations you must handle
- Undefined variable. An expression uses a name that is never assigned anywhere. The user of that name cannot be evaluated.
- Cyclic dependency. For example
foo = bar + 1andbar = foo + 1. None of the variables involved can be evaluated. - Partial results. In
ok = 1 bad = missing + 1okis fine butbadis not. Choose one policy and document it: either (a) fail the entire call if any variable is invalid, or (b) return everything that could be evaluated and report the rest separately.
Constraints
With N variables and M total tokens in all expressions, aim for O(N + M) time and space. Assume N and M can be large, so think about stack depth for long dependency chains.
What to deliver
- Working code in a language of your choice.
- A short explanation of how you represent the dependency graph, in what order you evaluate, how you detect undefined names and cycles, and the time and space complexity.
Hints
Hint 1
Separate the work into parsing (turning each line into a name plus a list of signed terms) and evaluation (deciding the order in which variables can be computed).
Hint 2
Treat 'x uses y' as an edge y -> x. A variable is ready once all variables it uses have values, which is exactly the situation topological sorting with in-degrees (Kahn's algorithm) handles iteratively.
Hint 3
Anything that never reaches in-degree zero is on a cycle or depends on one, and a reference to a name with no assignment can be flagged while building the graph. Deduplicate dependencies per variable so that `a = b + b` does not inflate the in-degree.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat this as a small parser followed by a dependency-resolution problem on a directed graph.
- Parse every line into a target name and a list of signed terms. A term is either an integer literal or a variable reference. Subtraction is stored as a term with sign
-1, so left-to-right evaluation is just a sum of signed terms. - Build the graph. For each variable
vand each distinct namedin its expression, add an edged -> v. Keep an in-degree count per variable equal to the number of distinct defined dependencies. - Evaluate in topological order with Kahn's algorithm. Start with variables of in-degree zero (pure literals, or only invalid inputs), pop one, compute its value from its terms, then decrement the in-degree of each dependent and enqueue those that reach zero.
Kahn's algorithm is iterative, so a chain of 100,000 variables cannot overflow the call stack, which is the main weakness of a recursive DFS with memoization.
Contract (state this up front)
- Malformed syntax (bad identifier,
a = 1 +,a = 1 2, a duplicate assignment) raises a syntax error immediately. There is no useful partial result for text that does not parse. - Partial evaluability: option (b), fail-loud. If everything evaluates, return the map. If anything fails, raise an error object that carries both the computed values and a per-variable reason. Callers cannot silently ignore a failure but can still recover what was computable.
- Whitespace separates tokens rather than being deleted, so
foo baris an error and not the identifierfoobar. - A single leading sign (
x = -5 + y) is accepted. Doubled operators such as1 + - 2are rejected.
Handling the error cases
- Undefined names. While building the graph, a reference with no assignment marks the referencing variable invalid with reason "undefined: name". That variable still gets processed so its dependents learn they are affected.
- Propagation. When a variable is dequeued and any of its dependencies is invalid, it becomes invalid as well, with a reason that names the bad dependency.
- Cycles. Any variable never dequeued still has a positive in-degree, so it lies on a cycle or downstream of one. Report these as cyclic dependency errors. Self-reference (
a = a + 1) is caught naturally becauseahas an in-degree contribution from itself.
If you need to distinguish "on a cycle" from "merely depends on a cycle", run Tarjan's strongly connected components algorithm over the leftover nodes. It is still O(N + M).
Why it is correct
- A node enters the queue only when all its defined dependencies are processed, so each one already has either a value or an error recorded. Evaluation is therefore well-founded.
- If a variable's whole dependency closure has no undefined names and no cycle, induction on the longest dependency path shows every node in that closure is eventually dequeued, so it gets a value.
- Any node left over must have an unprocessed predecessor. Walking backwards through a finite graph must repeat a node, which yields a cycle. Conversely, a node on a cycle can never reach in-degree zero.
Code (Python)
import re
from collections import deque, defaultdict
TOKEN = re.compile(r"(?P<id>[A-Za-z_][A-Za-z0-9_]*)|(?P<num>\d+)|(?P<op>[+-])")
IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
class EvaluationError(Exception):
def __init__(self, values, errors):
self.values, self.errors = values, errors
super().__init__("; ".join(f"{k}: {v}" for k, v in sorted(errors.items())))
def parse_expr(expr, lineno):
terms, pos, n = [], 0, len(expr)
sign, want_operand = None, True
while True:
while pos < n and expr[pos].isspace():
pos += 1
if pos == n:
break
m = TOKEN.match(expr, pos)
if not m:
raise SyntaxError(f"line {lineno}: bad character {expr[pos]!r}")
pos = m.end()
if m.group("op"):
s = 1 if m.group("op") == "+" else -1
if want_operand and (terms or sign is not None):
raise SyntaxError(f"line {lineno}: unexpected operator")
sign, want_operand = s, True
else:
if not want_operand:
raise SyntaxError(f"line {lineno}: missing operator")
s = sign if sign is not None else 1
if m.group("id"):
terms.append((s, True, m.group("id")))
else:
terms.append((s, False, int(m.group("num"))))
sign, want_operand = None, False
if want_operand:
raise SyntaxError(f"line {lineno}: incomplete expression")
return terms
def evaluate(program):
exprs = {}
for i, raw in enumerate(program.splitlines(), 1):
line = raw.strip()
if not line:
continue
lhs, eq, rhs = line.partition("=")
name = lhs.strip()
if not eq or not IDENT.fullmatch(name):
raise SyntaxError(f"line {i}: invalid target")
if name in exprs:
raise SyntaxError(f"line {i}: duplicate assignment to {name}")
exprs[name] = parse_expr(rhs, i)
indeg = {v: 0 for v in exprs}
users = defaultdict(list)
errors, values = {}, {}
for v, terms in exprs.items():
deps = {t[2] for t in terms if t[1]}
for d in deps:
if d in exprs:
users[d].append(v)
indeg[v] += 1
else:
errors.setdefault(v, f"undefined variable '{d}'")
q = deque(v for v, k in indeg.items() if k == 0)
done = 0
while q:
v = q.popleft()
done += 1
if v not in errors:
total = 0
for s, is_var, x in exprs[v]:
if is_var:
if x in errors:
errors[v] = f"depends on invalid variable '{x}'"
break
total += s * values[x]
else:
total += s * x
else:
values[v] = total
for u in users[v]:
indeg[u] -= 1
if indeg[u] == 0:
q.append(u)
if done < len(exprs):
for v, k in indeg.items():
if k > 0:
errors[v] = "cyclic dependency"
if errors:
raise EvaluationError(values, errors)
return values
Complexity
- Time O(N + M). Tokenizing is linear in input size, graph construction adds at most one edge per reference, Kahn's algorithm touches each node and edge once, and each variable's terms are summed once.
- Space O(N + M) for parsed terms, adjacency lists, in-degrees, and results.
Python integers do not overflow. In Java or C++ use 64-bit integers, and decide whether overflow should be an error.
Edge cases and common mistakes
- Blank lines are skipped, and forward references need no special handling because all lines are parsed before evaluation.
- Duplicating edges for
a = b + bmakes in-degree too large and falsely reports a cycle. Deduplicate dependencies with a set. - Stripping all whitespace up front turns
foo barintofoobarand hides a syntax error. - Forgetting to propagate failure means a variable downstream of an undefined name gets a bogus value.
- Recursive DFS on a very long chain hits recursion limits. If you use DFS, use three colors (unvisited, in progress, done) and an explicit stack.
- Evaluating
a - b - casa - (b - c)is a classic bug. Store signs per term and sum.