↓Skip to main content
  1. LeetCode/

LeetCode 952: Largest Component Size by Common Factor

·2 mins· ·
LeetCode Hard Math Number-Theory Union-Find Hash-Table Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: hard First Attempt: 2025-05-10

  • Submissions: TLE ×2 → AC (2025-05-17) → TLE → AC ×2 (rewritten 2026-10-12)

Approach
#

Two numbers share a factor greater than 1 ⇔ they share a prime factor.

  • Pairwise GCDs are O(n^2 log M), too slow for n = 2 × 10^4.
  • Instead factor each number (trial division up to √x) and record each prime’s first owner index owner[p]. Later numbers with the same prime are unioned with owner[p].

Finally count each group’s size and take the maximum.

My Attempts
#

WhenVersionProblem
2025-05Two TLEsPairwise GCDs, O(n^2)
2025-05ACGrouped indices by prime factor and unioned neighbors within each group
2026-10TLEThe rewrite went back to pairwise GCDs
2026-10AC (3.9 s)Switched to owner[p], but find was return find(parent[a]) without storing it in parent[a], so there was no path compression
2026-10AC (1.3 s)Added path compression

Solution
#

class Solution:
    def largestComponentSize(self, nums: List[int]) -> int:
        n = len(nums)
        parent = list(range(n))

        def find(a: int) -> int:
            if parent[a] != a:
                parent[a] = find(parent[a])        # path compression: store it back
            return parent[a]

        def union(a: int, b: int) -> None:
            ra, rb = find(a), find(b)
            if ra != rb:
                parent[ra] = rb

        owner = {}                                 # prime factor -> first index that has it

        def link(i: int, p: int) -> None:
            if p in owner:
                union(i, owner[p])
            else:
                owner[p] = i

        for i, x in enumerate(nums):
            p = 2
            while p * p <= x:
                if x % p == 0:
                    link(i, p)
                    while x % p == 0:
                        x //= p
                p += 1
            if x > 1:
                link(i, x)                         # the leftover large prime factor

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

Complexity
#

Time O(n √M) (trial division) with M the maximum; an SPF sieve brings it to O(M + n log M). Space O(n + number of primes).

Mistakes to Avoid
#

  • Pairwise GCDs: O(n^2).
  • find not storing its result: no path compression.
  • A leftover x > 1 after trial division is a prime factor too.

Interview Explanation
#

Sharing a factor means sharing a prime factor, so instead of pairwise GCDs I factor each number, remember each prime’s first owner index, and union later numbers with the same prime using Union-Find. Then I count group sizes. Time O(n √M).

Related

LeetCode 3518: Smallest Palindromic Rearrangement II
·3 mins
LeetCode Hard Math Combinatorics Counting Hash-Table String
LeetCode 3518 note: a palindrome is determined by its left half, so this is the k-th permutation of a multiset; try characters position by position and use permutation counts, updated in O(1), to find k’s branch
LeetCode 1814: Count Nice Pairs in an Array
·1 min
LeetCode Medium Array Hash-Table Math Counting
LeetCode 1814 note: rearrange the condition into nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]), count pairs per value, and remember the modulus
LeetCode 204: Count Primes
·2 mins
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 note: the sieve of Eratosthenes, crossing out multiples of each prime p starting at p², with the outer loop only up to √n
LeetCode 128: Longest Consecutive Sequence
·2 mins
LeetCode Medium Array Hash-Table Union-Find
LeetCode 128 note: put everything in a set and count upward only from values whose x - 1 is absent; each value is seen at most twice, O(n)
LeetCode 914: X of a Kind in a Deck of Cards
·2 mins
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 note: every card count must be divisible by one X >= 2, i.e. the GCD of all counts is at least 2
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0