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 Factor461535GCD=2GCD=3GCD=5Connected ComponentAll 4 numbers connectedthrough shared factorsOutput: 4
Understanding the Visualization
1
Input
Array of unique positive integers [4,6,15,35]
2
Connect
Numbers connect if they share a common factor > 1
3
Output
Size of largest connected component: 4
Key Takeaway
🎯 Key Insight: Numbers form a connected graph through shared prime factors - use Union-Find for efficient component detection
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