Skip to content

Evaluate Division

MediumGraphs
Decode it first. Clues, constraints, pattern and plan before any code.

You get equations like a / b = 2.0: equations[i] = [a, b] with values[i] as the result, where every name stands for a positive number. Then for each query [c, d], return the value of c / d if the equations determine it, or -1.0 if they do not (including when a name never appears in any equation). Return all answers in query order.

equations = [["a", "b"], ["b", "c"]], values = [2.0, 3.0]
queries   = [["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]]
  →  [6.0, 0.5, -1.0, 1.0, -1.0]
  (a/c = a/b · b/c = 6, and "x" is unknown, so even x/x is -1)

Constraints

  • 1 <= equations.length <= 20
  • 1 <= queries.length <= 20
  • 0.0 < values[i] <= 20.0
  • The equations never contradict each other