CodingNodes / Graphs / Evaluate Division System design Space play · ←→ step · R restart

Problem

You are given a list of equations. Equation i says equations[i][0] / equations[i][1] = values[i], where the two names are variables and values[i] is a positive real number.

You are also given a list of queries. Each query [x, y] asks for the value of x / y. Return one number per query, using the equations to work it out. If a query cannot be answered, because a variable never appears in any equation or the two variables are not connected through the equations, its answer is -1.0.

The equations never contradict each other, and a variable divided by itself is 1.0 as long as the variable appears in some equation.

Constraints

  • 1 ≤ equations.length ≤ 20, values.length = equations.length
  • Each variable name is 1 to 5 lowercase letters or digits
  • 0.0 < values[i] ≤ 20.0
  • 1 ≤ queries.length ≤ 20
  • The equations are consistent: no result depends on which path is used

Examples: pick one to animate

Solutions

TimeO(E + Q · (V + E)) SpaceO(V + E)

Time: Building the graph touches every equation once. Each query then runs one BFS that visits every variable and edge at most once.

Space: The graph holds two edges per equation, and a single search needs a queue and a seen set of at most V variables.

Treat each variable as a node. The equation a / b = k becomes an edge a to b with weight k, plus the reverse edge b to a with weight 1 / k. To answer x / y, search from x and keep the product of the weights along the way: the product on the path to y is exactly x / y. If the search never reaches y, or either name is missing from the graph, the answer is -1.