Largest Component Size by Common Factor - Problem

You are given an integer array nums of unique positive integers. 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.

Input & Output

Example 1 — All Connected
$ Input: nums = [4,6,15,35]
Output: 4
💡 Note: 4 and 6 share factor 2, 6 and 15 share factor 3, 15 and 35 share factor 5. All numbers form one connected component of size 4.
Example 2 — Multiple Components
$ Input: nums = [20,50,9,63]
Output: 2
💡 Note: 20 and 50 share factor 2 and 5 (component size 2). 9 and 63 share factor 3 (component size 2). Largest component has size 2.
Example 3 — All Separate
$ Input: nums = [2,3,6,7,4,12,21,39]
Output: 8
💡 Note: Multiple numbers share common factors: 2-4-6-12, 3-6-12-21-39. All form one large connected component.

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • 1 ≤ nums[i] ≤ 105
  • All the values of nums are unique.

Visualization

Tap to expand
Largest Component Size by Common Factor INPUT nums = [4, 6, 15, 35] 4 6 15 35 Graph Representation 4 6 15 35 factor:2 factor:3 factor:5 All nodes connected! ALGORITHM STEPS 1 Prime Factorize Find primes of each num 4 = 2x2 (prime: 2) 6 = 2x3 (primes: 2,3) 15 = 3x5 (primes: 3,5) 35 = 5x7 (primes: 5,7) 2 Initialize Union-Find Create parent[] for each num 3 Union by Prime Same prime --> Union sets Prime 2: Union(4, 6) Prime 3: Union(6, 15) Prime 5: Union(15, 35) 4 Find Largest Count max component size All 4 numbers in one set! FINAL RESULT Connected Component 4 6 15 35 Output: 4 OK - All nodes connected Largest component = 4 nodes Key Insight: Union-Find groups numbers by shared prime factors. Instead of checking GCD for all pairs (O(n^2)), we map each number to its prime factors and union numbers sharing the same prime. Time: O(n * sqrt(max)) for factorization. The chain: 4--2--6--3--15--5--35 connects all! TutorialsPoint - Largest Component Size by Common Factor | Union-Find with Prime Factorization
Asked in
Google 15 Amazon 12 Facebook 8
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen