sagelearnai

Evaluate Division

Difficulty: Medium · Pattern: Union-Find · LeetCode #399

equations[i] = [A, B] with values[i] = k means A / B = k. For each query [C, D], return C / D, or -1.0 if it can't be determined (including when a variable has never appeared). Answers are compared to 5 decimal places.

Example

text
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]

Hints

  1. Graph view: an edge A→B with weight k and B→A with 1/k. A query is the product of the weights along any path. That's DFS/BFS per query.
  2. Union-Find view: store weight[x] = x / parent(x) and keep the weights consistent through path compression.

Approach

Weighted Union-Find:

  • find(x) returns (root, x / root), compressing the path and multiplying the weights along the way.
  • union(a, b, k) (meaning a / b = k): find (ra, wa) and (rb, wb), where wa = a/ra and wb = b/rb. Since ra = a / wa and rb = b / wb, linking ra → rb needs weight[ra] = ra / rb = (a / b) · (wb / wa) = k · wb / wa.
  • Query (c, d): if either is unknown or their roots differ, return −1. Otherwise return wc / wd.

That's near O(1) per operation. The DFS alternative (O(V+E) per query) is the one most people code first and is perfectly acceptable for small inputs.

Complexity

Time: O((E + Q) · α) with Union-Find, O(Q · (V + E)) with DFS. Space: O(V).

Python solution
def calcEquation(equations, values, queries):
    parent, weight = {}, {}
    def find(x):
        if parent[x] != x:
            root, w = find(parent[x])
            parent[x] = root
            weight[x] *= w
        return parent[x], weight[x]
    for (a, b), k in zip(equations, values):
        for v in (a, b):
            if v not in parent:
                parent[v], weight[v] = v, 1.0
        ra, wa = find(a)
        rb, wb = find(b)
        if ra != rb:
            parent[ra] = rb
            weight[ra] = k * wb / wa
    res = []
    for c, d in queries:
        if c not in parent or d not in parent:
            res.append(-1.0)
            continue
        rc, wc = find(c)
        rd, wd = find(d)
        res.append(wc / wd if rc == rd else -1.0)
    return res
JavaScript solution
function calcEquation(equations, values, queries) {
  const adj = new Map();
  const add = (a, b, w) => { if (!adj.has(a)) adj.set(a, []); adj.get(a).push([b, w]); };
  equations.forEach(([a, b], i) => { add(a, b, values[i]); add(b, a, 1 / values[i]); });
  const query = (c, d) => {
    if (!adj.has(c) || !adj.has(d)) return -1;
    const seen = new Set([c]), stack = [[c, 1]];
    while (stack.length) {
      const [u, acc] = stack.pop();
      if (u === d) return acc;
      for (const [v, w] of adj.get(u)) if (!seen.has(v)) { seen.add(v); stack.push([v, acc * w]); }
    }
    return -1;
  };
  return queries.map(([c, d]) => query(c, d));
}