Largest Component Size by Common Factor - Problem
You're given an array nums of unique positive integers. Your task is to find connected groups where numbers are linked if they share a common factor greater than 1.
Think of this as a friendship network where two numbers are friends if they have a common factor greater than 1. For example, 6 and 15 are friends because they both share the factor 3.
Goal: Return the size of the largest connected group in this network.
Example: In [4, 6, 15, 35]:
4and6share factor2→ connected6and15share factor3→ connected15and35share factor5→ connected- All four numbers form one connected component of size 4
Input & Output
example_1.py — Basic Case
$
Input:
[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.
example_2.py — Multiple Components
$
Input:
[20,50,9,63]
›
Output:
2
💡 Note:
20 and 50 share factor 2 and 5 (component size 2). 9 and 63 share factor 3 and 9 (component size 2). Maximum is 2.
example_3.py — All Prime Numbers
$
Input:
[2,3,6,7,4,12,21,39]
›
Output:
8
💡 Note:
2-6-4-12 connected by factor 2, 3-6-12-21-39 connected by factor 3, creating one large component through number 6 and 12.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Interests
Find prime factors for each number (person's interests)
2
Connect Through Interests
Numbers sharing prime factors get connected
3
Find Largest Group
Union-Find tracks the largest connected component
Key Takeaway
🎯 Key Insight: Connect numbers through prime factors rather than direct GCD checks, reducing complexity from O(n²) to O(n√max)
Time & Space Complexity
Time Complexity
O(n² * log(max(nums)))
O(n²) pairs × O(log(max)) for GCD computation + O(n²) for DFS
⚠ Quadratic Growth
Space Complexity
O(n²)
Adjacency list can have O(n²) edges in worst case
⚠ Quadratic Space
Constraints
- 1 ≤ nums.length ≤ 2 × 104
- 1 ≤ nums[i] ≤ 105
-
All values in
numsare unique
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code