FastPrepResolve Variable Equations with Dependency Errors

Resolve Variable Equations with Dependency Errors

Motive logoMotive● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

You are given an array of variable definitions. Each definition has the form name = term + term + .... 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 +.

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.

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.

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.

Constraints

  • 1 <= equations.length <= 1000
  • Every variable name contains between 1 and 30 lowercase English letters.
  • Each variable is defined exactly once.
  • Each expression contains between 1 and 100 terms joined by +.
  • Integer terms are in the range [-10^9, 10^9].
  • Every successfully resolved value fits in a signed 64-bit integer.

More Motive problems

See Motive hiring insights
public String[] resolveEquations(String[] equations) {
  // write your code here
}
equations["foo = bar + 5", "bar = 2", "abc = 3"]
expected["foo=7", "bar=2", "abc=3"]
Checking account…