Resolve Variable Equations with Dependency Errors
Problem statement
You are given an array of variable definitions. Each definition has the form name = term + term - term + ..., with addition or subtraction between consecutive terms. A term is either a signed integer or the name of another variable. Variable names contain only lowercase English letters. Whitespace may appear around names, integers, =, and operators. Expressions contain no parentheses.
Resolve every variable and return one string per definition, in the same order as the input. Each successful result must have the form name=value. Addition and subtraction are evaluated from left to right. A minus sign immediately before an integer belongs to that signed term, so foo - -3 subtracts negative three.
If the dependency graph among defined variables contains any cycle, return the one-element array ["Cyclic Dependency"]. Otherwise, if any expression references a variable that is not defined, return ["Unresolvable equations"]. A cycle takes precedence when both conditions occur.
Operator extension discussion
The exercise begins with addition, then adds subtraction. As a design follow-up, explain how you would add multiplication and division while making precedence, division-by-zero behavior and numeric precision explicit. These additional operators are a discussion follow-up; judged expressions use only addition and subtraction.
Function
resolveEquations(equations: String[]) → String[]Examples
Example 1
equations = ["foo = bar + 5", "bar = 2", "abc = 3"]return = ["foo=7", "bar=2", "abc=3"]bar resolves to 2, so foo resolves to 2 + 5 = 7. Results retain definition order.
Example 2
equations = ["g = abc + foo", "foo = bar + 5", "bar = 2", "abc = 3"]return = ["g=10", "foo=7", "bar=2", "abc=3"]Depth-first dependency resolution gives foo = 7, then g = 3 + 7 = 10.
Example 3
equations = ["foo = bar + 3", "bar = abc + pqr + 2"]return = ["Unresolvable equations"]Neither abc nor pqr is defined, so the equations cannot be resolved.
Example 4
equations = ["foo = bar + 3", "bar = foo + 2"]return = ["Cyclic Dependency"]foo depends on bar, and bar depends on foo, forming a cycle.
Example 5
equations = ["foo = bar - 5","bar = 2","abc = foo - -3"]return = ["foo=-3","bar=2","abc=0"]bar = 2 gives foo = 2 - 5 = -3. Then abc = -3 - (-3) = 0. Results keep the original definition order.
Constraints
1 <= equations.length <= 1000.- Every variable name contains between
1and30lowercase English letters. - Each variable is defined exactly once.
- Each expression contains between
1and100signed-integer or variable terms joined by+or-; every expression follows the documented grammar. - Integer terms are in the range
[-10^9, 10^9]. - For this exercise, assume every intermediate arithmetic result and successfully resolved value fits in a signed 64-bit integer.