Largest Component Size by Common Factor — LeetCode 952 Python Solution

HardUnion FindArrayHash TableMathNumber Theory
Problem
#952
Pattern
Union-Find
Reading time
5 min

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

Python
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

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview