SDE & MLE Prep

399. Evaluate Division

Problem

equations[i] = [A, B] with values[i] means A / B = values[i]. For each query [C, D], return C / D, or −1.0 if it can't be determined (including any variable that never appears). The equations never contradict each other.

Example: a / b = 2.0, b / c = 3.0; queries a/c, b/a, a/e, a/a, x/x → [6.0, 0.5, -1.0, 1.0, -1.0]

a / b = 2 ⇒ edges a→b (2) and b→a (0.5). A query x / y = product of weights along any path from x to y (DFS/BFS). Unknown variable or no path → −1.

Complexity: O(Q · (V + E)).

class Solution:
    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
        g = defaultdict(dict)
        for (a, b), v in zip(equations, values):
            g[a][b] = v
            g[b][a] = 1 / v

        def dfs(x, y, seen):
            if x == y:
                return 1.0
            seen.add(x)
            for nb, w in g[x].items():
                if nb not in seen:
                    r = dfs(nb, y, seen)
                    if r != -1:
                        return w * r
            return -1.0

        return [dfs(x, y, set()) if x in g and y in g else -1.0 for x, y in queries]