Evaluate Division

Solution Code
class Solution:
    def calcEquation(self, equations: list[list[str]], values: list[float], queries: list[list[str]]) -> list[float]:
        parent, ratio = {}, {}
        def find(x):
            if x not in parent:
                parent[x], ratio[x] = x, 1.0
            if parent[x] != x:
                orig_parent = parent[x]
                parent[x], ratio[x] = find(parent[x]), ratio[x] * ratio[orig_parent]
            return parent[x]
        def union(x, y, val):
            root_x, root_y = find(x), find(y)
            if root_x != root_y:
                parent[root_x] = root_y
                ratio[root_x] = val * ratio[y] / ratio[x]
        for (u, v), val in zip(equations, values):
            union(u, v, val)
        ans = []
        for u, v in queries:
            if u not in parent or v not in parent or find(u) != find(v):
                ans.append(-1.0)
            else:
                ans.append(ratio[u] / ratio[v])
        return ans
Video GuideLeetcode Daily

Time Complexity

O(N Q)

Space Complexity

O(N)