#952
Largest Component Size by Common Factor
HardArrayHash TableMathUnion-FindNumber TheoryHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log k) where k is the number of unique prime factors across all numbers. |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log k) where k is the number of unique prime factors across all numbers.Space O(n)
The optimal approach leverages the Union-Find data structure to efficiently group numbers that share common factors. This allows us to quickly find and union components without explicitly constructing a graph.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a Union-Find structure to manage connected components.
- 2Step 2: For each number, find all its prime factors.
- 3Step 3: Union all numbers that share the same prime factor.
- 4Step 4: Count the size of each component using the Union-Find structure.
- 5Step 5: Return the size of the largest component.
solution.py49 lines
1# Full working Python code
2from collections import defaultdict
3
4class UnionFind:
5 def __init__(self, size):
6 self.parent = list(range(size))
7 self.rank = [1] * size
8
9 def find(self, x):
10 if self.parent[x] != x:
11 self.parent[x] = self.find(self.parent[x])
12 return self.parent[x]
13
14 def union(self, x, y):
15 rootX = self.find(x)
16 rootY = self.find(y)
17 if rootX != rootY:
18 if self.rank[rootX] > self.rank[rootY]:
19 self.parent[rootY] = rootX
20 elif self.rank[rootX] < self.rank[rootY]:
21 self.parent[rootX] = rootY
22 else:
23 self.parent[rootY] = rootX
24 self.rank[rootX] += 1
25
26def largestComponentSize(nums):
27 max_num = max(nums)
28 uf = UnionFind(max_num + 1)
29 prime_to_index = defaultdict(list)
30
31 for num in nums:
32 for factor in range(2, int(num**0.5) + 1):
33 if num % factor == 0:
34 prime_to_index[factor].append(num)
35 while num % factor == 0:
36 num //= factor
37 if num > 1:
38 prime_to_index[num].append(num)
39
40 for indices in prime_to_index.values():
41 for i in range(1, len(indices)):
42 uf.union(indices[0], indices[i])
43
44 component_size = defaultdict(int)
45 for num in nums:
46 root = uf.find(num)
47 component_size[root] += 1
48
49 return max(component_size.values())ℹ
Complexity note: This complexity arises from the need to process each number and its prime factors, leading to efficient unions and finds in the Union-Find structure.
- 1Understanding prime factorization is crucial for connecting components.
- 2Union-Find is a powerful tool for managing dynamic connectivity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.