HardNo. 0952
Largest Component Size by Common Factor — LeetCode 952 Python Solution
- Pattern
- Union-Find
- Topics
- Union Find, Array, Hash Table, Math, Number Theory
- Reading time
- 5 min
- Source
- leetcode.com
The problem
You are given an integer array of unique positive integers nums. Consider the following graph: There are nums.length nodes, labeled nums[0] to nums[nums.length - 1], There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.
Example
- Input
- nums = [4,6,15,35]
- Output
- 4
Python solution
class UnionFind:
def __init__(self, n):
self.p = list(range(n))
def union(self, a, b):
pa, pb = self.find(a), self.find(b)
if pa != pb:
self.p[pa] = pb
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
class Solution:
def largestComponentSize(self, nums: List[int]) -> int:
uf = UnionFind(max(nums) + 1)
for v in nums:
i = 2
while i <= v // i:
if v % i == 0:
uf.union(v, i)
uf.union(v, v // i)
i += 1
return max(Counter(uf.find(v) for v in nums).values())Complexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 952. Largest Component Size by Common Factor is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.
The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0914 | X of a Kind in a Deck of Cards | Easy |
| 1994 | The Number of Good Subsets | Hard |
| 2001 | Number of Pairs of Interchangeable Rectangles | Medium |
| 2521 | Distinct Prime Factors of Product of Array | Medium |
| 2584 | Split the Array to Make Coprime Products | Hard |
| 2748 | Number of Beautiful Pairs | Easy |
Frequently asked questions
- How hard is LeetCode 952. Largest Component Size by Common Factor?
LeetCode 952. Largest Component Size by Common Factor is rated Hard on LeetCode.
- What is the time complexity of LeetCode 952. Largest Component Size by Common Factor?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 952. Largest Component Size by Common Factor?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 952. Largest Component Size by Common Factor cover?
LeetCode 952. Largest Component Size by Common Factor is tagged Union Find, Array, Hash Table, Math and Number Theory on LeetCode.