Skip to content

952. Largest Component Size by Common Factor

Difficulty Topics

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.

Solution

largest-component-size-by-common-factor.py
class DSU:
    def __init__(self, n):
        self.graph = list(range(n))

    def find(self, x):
        if self.graph[x] != x:
            self.graph[x] = self.find(self.graph[x])

        return self.graph[x]

    def union(self, x, y):
        ux, uy = self.find(x), self.find(y)
        self.graph[ux] = uy

class Solution:
    def largestComponentSize(self, nums: List[int]) -> int:
        n = len(nums)
        dsu = DSU(n)
        primes = defaultdict(list)

        def getPrimesSet(x):
            for i in range(2, int(math.sqrt(x)) + 1):
                if x % i == 0:
                    return getPrimesSet(x // i) | set([i])

            return set([x])

        for i, x in enumerate(nums):
            p = getPrimesSet(x)
            for prime in p:
                primes[prime].append(i)

        for indexes in primes.values():
            for x, y in zip(indexes, indexes[1:]):
                dsu.union(x, y)

        return max(Counter(dsu.find(i) for i in range(n)).values())