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]:

  • 4 and 6 share factor 2 → connected
  • 6 and 15 share factor 3 → connected
  • 15 and 35 share factor 5 → 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
Numbers Connected by Prime Factors4615352352×33×55×7Prime Factor 2Prime Factor 3Prime Factor 5Connected Component of Size 4Union-Find efficiently merges: 4↔6 (factor 2) → 6↔15 (factor 3) → 15↔35 (factor 5)
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

n
2n
Quadratic Growth
Space Complexity
O(n²)

Adjacency list can have O(n²) edges in worst case

n
2n
Quadratic Space

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • 1 ≤ nums[i] ≤ 105
  • All values in nums are unique
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
32.5K Views
Medium Frequency
~25 min Avg. Time
1.2K 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