Skip to problem
←

Evaluate Division

Medium 0 attempts

Use the given equations to evaluate each division query. An equation [a, b] with value v means a / b = v; the equations are consistent.

Return -1 when the ratio cannot be determined, including when either variable does not occur in any equation. A known variable divided by itself is 1; an unknown variable divided by itself is still -1. Return answers in the same order as the queries.

Function contract

equations[i] = [a, b] means a / b = values[i]. queries contains pairs [c, d] asking for c / d.

Output: Return one number per query in input order, or -1 when the ratio cannot be determined. Numeric answers use tolerance 0.00001 × max(1, |expected|).

Example 1

Input
equations = [["a","b"],["b","c"]]
values = [2,3]
queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
Output
[6,0.5,-1,1,-1]

Example 2

Input
equations = [["x","y"]]
values = [4]
queries = [["y","x"],["x","z"]]
Output
[0.25,-1]
Visual Aid
Multiply ratios along a path
abc23a / c = 2 × 3 = 6

Reverse an edge by taking its reciprocal: c / a = 1/6. Variables in different components have no known ratio.

Constraints
  • 1 <= equations.length, queries.length <= 20
  • values.length equals equations.length; 0 < values[i] <= 20
  • Every equation and query contains two nonempty variable names.
  • The equations are consistent and involve no division by zero.
Topics

Graph DFS

Build a weighted graph, DFS from dividend to divisor multiplying weights.

javascript
function calcEquation(equations, values, queries) {
  const graph = new Map();
  for (let i = 0; i < equations.length; i++) {
    const [a, b] = equations[i],
      v = values[i];
    if (!graph.has(a)) graph.set(a, []);
    if (!graph.has(b)) graph.set(b, []);
    graph.get(a).push([b, v]);
    graph.get(b).push([a, 1 / v]);
  }
  function dfs(src, dst, visited) {
    if (!graph.has(src) || !graph.has(dst)) return -1;
    if (src === dst) return 1;
    visited.add(src);
    for (const [next, w] of graph.get(src)) {
      if (visited.has(next)) continue;
      const res = dfs(next, dst, visited);
      if (res !== -1) return w * res;
    }
    return -1;
  }
  return queries.map(([a, b]) => dfs(a, b, new Set()));
}

Time: O(Q × (V + E)) | Space: O(V + E)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript