LeetCode 0952. Largest Component Size by Common Factor Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
0952. Largest Component Size by Common Factor

Description

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.

Return the size of the largest connected component in the graph.

 

Example 1:

Input: nums = [4,6,15,35]
Output: 4

Example 2:

Input: nums = [20,50,9,63]
Output: 2

Example 3:

Input: nums = [2,3,6,7,4,12,21,39]
Output: 8

 

Constraints:

  • 1 <= nums.length <= 2 * 104
  • 1 <= nums[i] <= 105
  • All the values of nums are unique.

Solutions

Solution 1

PythonJavaC++Go
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())(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !