Python 0952.py
class Solution:
def largestComponentSize(self, nums: List[int]) -> int:
# union-find, copied from problem 721, modified
parent = {}
def find(x):
if x not in parent: # default parent
parent[x] = x
return x
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
def union(x, y):
parent[find(x)] = find(y)
for n in nums:
# only if not already part of a graph
if find(n) == n:
# factorize
smaller = n
for factor in chain([ 2 ], range(3, n, 2)): # 2,3,5,7,9,11,13,...
if factor * factor > smaller:
break
while smaller % factor == 0:
if factor > 1: # avoid union with 1
union(n, factor)
smaller //= factor
# last prime
if smaller > 1:
union(n, smaller)
same = defaultdict(int)
for n in nums:
same[find(n)] += 1
return max(same.values())
Difficulty
and has an acceptance rate of about 43% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Math
- Number Theory
- Union Find
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation computes the size of the largest connected component among a list of integers where two numbers belong to the same component if they share a common factor greater than one. It builds an implicit graph using a union-find (disjoint-set) structure, merges numbers that share prime factors, and finally counts the members of each set to return the maximum size.
Core Union-Find Structure
A dictionary stores the parent of each element, allowing the structure to grow dynamically as new values appear. The find routine performs path compression, ensuring that subsequent look-ups reach the root quickly. The union routine links the roots of two elements, effectively merging their sets.
parent = {}
def find(x):
if x not in parent: # first encounter, become its own root
parent[x] = x
return x
if parent[x] != x: # compress the path
parent[x] = find(parent[x])
return parent[x]
def union(x, y):
parent[find(x)] = find(y) # attach root of x to root of y
Factorization and Merging
For each number the algorithm attempts to factorize it only when the number is currently a root in the union-find forest. This prevents repeated work for duplicate values. The factorization iterates over potential divisors starting with 2 and then all odd numbers up to the square root of the remaining value. When a divisor evenly divides the current remainder, the algorithm repeatedly divides it out and unions the original number with the divisor, provided the divisor is greater than one. After the loop, any leftover value greater than one is a prime factor and is also united with the original number.
for n in nums:
if find(n) == n: # process only if n is a root
smaller = n
for factor in chain([2], range(3, n, 2)):
if factor * factor > smaller:
break
while smaller % factor == 0:
if factor > 1: # skip union with 1
union(n, factor)
smaller //= factor
if smaller > 1: # last remaining prime factor
union(n, smaller)
Edge Cases Handled
The code explicitly avoids creating a union with the value 1, ensuring that numbers consisting solely of the factor 1 (i.e., the integer 1 itself) remain isolated. When a number is prime, the inner loop finishes without finding a divisor, and the final if smaller > 1 clause unions the number with its sole prime factor, effectively linking the number to itself in the disjoint set. Duplicate entries in the input list do not trigger additional factorization because the find(n) == n guard processes each distinct value only once; later occurrences simply contribute to the size count of the already-formed component.
Counting Component Sizes
After all unions are performed, a defaultdict tallies how many original numbers map to each root. The maximum count among these tallies is the answer.
same = defaultdict(int)
for n in nums:
same[find(n)] += 1
return max(same.values())
Performance Optimizations
Path compression inside find flattens the tree structure, making future find operations near-constant time. The early termination condition if factor * factor > smaller: break stops the divisor search as soon as the remaining value cannot have a smaller factor, reducing unnecessary iterations. By iterating only over odd numbers after handling 2, the algorithm halves the number of candidate divisors. The guard if find(n) == n prevents repeated factorization of numbers that have already been merged, which is especially beneficial when the input contains many duplicates. The use of a dictionary for parent allows on-the-fly creation of nodes without pre-allocating a large array, keeping memory usage proportional to the distinct values and their prime factors.
ELI5 - Simplified Explanation
Imagine a big playground where all the numbers are trying to find friends. Some numbers share special secrets called factors, which are like secret handshakes. When two numbers share the same secret handshake, they become part of the same team.
The code starts by giving every number its own little spot. Then, it looks at each number one by one to see if it can break that number down into smaller pieces. Think of it like taking a lego tower apart to see what blocks were used to build it. If a number is made of certain blocks, it connects to other numbers that are made of those same blocks.
The union part is just the way the numbers hold hands to form a big group. If number six has a secret handshake with two, it joins the group that two belongs to. By the time every number has been checked for these secret connections, there are several different teams gathering in the playground.
Finally, the code looks at all the teams to see which group has the most friends in it. It counts how many numbers are standing together in each group and picks the largest one to show which team is the biggest of all.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | ||||
| LeetcodeHelp | C++ | Python | Java | |||||
| Progiez | C++ | Python | Java | |||||
| github | BigEggStudy | C# | ||||||
| black-shadows | C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| gouthampradhan | Java | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| XiaotaoGuo | C++ | |||||||
| YuriSpiridonov | Python | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| LeetcodeHelp | C++, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| BigEggStudy | C# | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| gouthampradhan | Java | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| XiaotaoGuo | C++ | |||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2157: Groups of Strings
- problem 2521: Distinct Prime Factors of Product of Array
Solved On The Same Day
- problem 1894: Find the Student that Will Replace the Chalk
- problem 940: Distinct Subsequences II
- problem 972: Equal Rational Numbers
- problem 1001: Grid Illumination
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality