Largest Component Size by Common Factor — LeetCode 952 Python Solution
- Problem
- #952
- Pattern
- Union-Find
- 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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
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.