#399

Evaluate Division

Medium
ArrayStringDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryShortest PathGraph TraversalUnion-FindDepth-First Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * α(n))
Space
O(1)
O(n)
💡

Intuition

Time O(n * α(n))Space O(n)

The optimal solution leverages graph traversal with a union-find structure to efficiently find the relationships between variables. This is like having a map with direct routes, allowing us to quickly find the shortest path between two points.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build a graph using a union-find data structure to connect variables based on the equations.
  2. 2Step 2: For each query, check if both variables are in the same connected component.
  3. 3Step 3: If they are connected, calculate the value using the stored products; otherwise, return -1.0.
solution.py36 lines
1# Full working Python code
2class UnionFind:
3    def __init__(self):
4        self.parent = {}
5        self.value = {}
6
7    def find(self, x):
8        if self.parent[x] != x:
9            origin = self.find(self.parent[x])
10            self.value[x] *= self.value[self.parent[x]]
11            self.parent[x] = origin
12        return self.parent[x]
13
14    def union(self, x, y, value):
15        if x not in self.parent:
16            self.parent[x] = x
17            self.value[x] = 1.0
18        if y not in self.parent:
19            self.parent[y] = y
20            self.value[y] = 1.0
21        rootX = self.find(x)
22        rootY = self.find(y)
23        self.parent[rootX] = rootY
24        self.value[rootX] = value * self.value[y] / self.value[x]
25
26def calcEquation(equations, values, queries):
27    uf = UnionFind()
28    for (a, b), value in zip(equations, values):
29        uf.union(a, b, value)
30    results = []
31    for c, d in queries:
32        if c in uf.parent and d in uf.parent and uf.find(c) == uf.find(d):
33            results.append(uf.value[c] / uf.value[d])
34        else:
35            results.append(-1.0)
36    return results

Complexity note: The time complexity is O(n * α(n)) where α(n) is the inverse Ackermann function, which grows very slowly, making this approach efficient. The space complexity is O(n) due to the storage of parent and value mappings.

  • 1Understanding the problem as a graph allows for efficient traversal and relationship mapping.
  • 2Union-Find is particularly useful for dynamic connectivity problems, where we need to group elements based on relationships.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.