Largest Component Size by Common Factor
Join each number to its prime factors with union-find, and find the largest group of numbers linked by shared factors.
Given an array nums
Example 1
Output: 4
Explanation: 4 and 6 share 2, 6 and 15 share 3, 15 and 35 share 5, so all four numbers are in one group.
Example 2
Output: 2
Explanation: 20 and 50 share 2, 5 and 10, and 9 and 63 share 3 and 9. No number of the first pair shares a factor with one of the second.
The Idea
Every whole number above 1 can be written as a product of primes, the numbers that only 1 and themselves divide: 6 is 2 × 3, 15 is 3 × 5 and 35 is 5 × 7. Think of each prime as a club, and of each number as a member of the club of every prime in it. 6 is then in the 2 club and the 3 club, and 15 in the 3 club and the 5 club.
Two numbers have a common factor greater than 1 exactly when they are in the same club. If some d greater than 1 divides both, then any prime in d divides both as well. 6 and 15 have the common factor 3, and both are in the 3 club.
Now look at Example 1 again. 4 and 35 have no common factor at all, yet the answer puts all four numbers in one group. 4 shares 2 with 6, 6 shares 3 with 15, and 15 shares 5 with 35, so a chain of lines reaches from 4 to 35. How can we find chains like this without testing every pair of numbers?
Join each number to its own prime factors instead, and let the primes do the linking. Look at the picture below.
The row labelled input numbers holds 4, 6, 15 and 35, and the row labelled prime factors holds 2, 3, 5 and 7. Each number has a line to every prime in it. 6 and 15 are never compared with each other, but the two orange lines show both of them joining 3. Following the lines from 4 through 2, 6, 3, 15 and 5 reaches 35, so all four numbers land in one group.
So the groups we want are the groups in this picture, with the primes left out when we count. Each number has only a few prime factors, so it needs only a few lines, however many other numbers there are.
Solution Approach
Comparing every pair of numbers directly is the obvious alternative, and it is slow. Joining numbers to primes instead means settling three things: how to keep track of the groups while lines are added, how to find each number's prime factors, and how to count only the input numbers.
Comparing every pair
Why not compare every two numbers and draw a line when they share a factor? One pair is quick to check, because the largest number that divides both is above 1 exactly when they share a factor. But 10,000 numbers make about 50 million pairs, and the groups would still have to be found after that.
Keeping track of the groups
How do we know which group a value is in while lines keep being added? Give every value from 0 up to the largest input number, maxparent
At the start, every value is its own parent, so each one is a group on its own. Following parents upward from a value ends at a value that is its own parent, called the root, and the root names the group. To join two values, take the root of each and make one root the parent of the other. Finding roots and joining groups this way is called union-find.
Take Example 1. Joining 4 with 2 sets parent[4] = 2parent[6] = 2parent[2] = 3
The chains of parents can grow long. So while the method that finds a root, named find
Finding the prime factors
How do we get a number's prime factors? Try dividing by f = 2, 3, 4 and so on. When f divides the number, f is a prime factor, and we divide every copy of it out. That way a number such as 4 can never divide what is left, because its 2s are already gone. The part still to be factored is kept in rest
We can stop once f × f is larger than restrestrestrest
Counting only the input numbers
Which values count towards the answer? The primes are only go-betweens. In the picture, the group holds eight values, but only four of them, 4, 6, 15 and 35, are input numbers. So after all the joins, we find the root of each input number and count how many input numbers share each root. The largest count is the answer.
Java Solution
The method largestComponentSize
- First, find the largest number,
, and createmax withparent entries, setting each value as its own parent.max + 1 - Go through the numbers with a loop. For each number
, copy it intox , and inside, a second loop tries divisorsrest from 2 whilef . Whenf * f <= rest dividesf , the helperrest joinsunion withx , and every copy off is divided out off .rest - After the divisor loop, if
, joinrest > 1 withx , the leftover prime.rest - Then create a map named
, from root to the number of input numbers with that root. For eachcount , the helperx gives its root,find adds one for that root, andcount.merge keeps the largest count seen.best - When every number is counted, return
.best
The main[1, 5, 7]
import java.util.HashMap;
import java.util.Map;
public class LargestComponentSizeByCommonFactor {
public static int largestComponentSize(int[] nums) {
int max = 0;
for (int x : nums) {
max = Math.max(max, x);
}
int[] parent = new int[max + 1]; // one entry for every value up to max
for (int i = 0; i <= max; i++) {
parent[i] = i; // every value starts as its own group
}
for (int x : nums) {
int rest = x;
for (int f = 2; f * f <= rest; f++) {
if (rest % f == 0) {
union(parent, x, f); // f is a prime factor of x
while (rest % f == 0) {
rest /= f; // divide out every copy of f
}
}
}
if (rest > 1) {
union(parent, x, rest); // one prime factor larger than sqrt(x)
}
}
Map<Integer, Integer> count = new HashMap<>();
int best = 0;
for (int x : nums) {
int c = count.merge(find(parent, x), 1, Integer::sum);
best = Math.max(best, c);
}
return best;
}
private static int find(int[] parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]]; // point to the grandparent: shorter paths
x = parent[x];
}
return x;
}
private static void union(int[] parent, int a, int b) {
parent[find(parent, a)] = find(parent, b);
}
public static void main(String[] args) {
System.out.println(largestComponentSize(new int[] {4, 6, 15, 35}));
System.out.println(largestComponentSize(new int[] {20, 50, 9, 63}));
System.out.println(largestComponentSize(new int[] {2, 3, 6, 7, 4, 12, 21, 39}));
System.out.println(largestComponentSize(new int[] {14, 21}));
System.out.println(largestComponentSize(new int[] {1, 5, 7}));
}
}
Running it prints:
4
2
8
2
1
Example 1 gives 4 and Example 2 gives 2, as the problem expects. The 8 on the third line covers all of [2, 3, 6, 7, 4, 12, 21, 39]parent
The fourth line, 2, depends on the leftover step. 14 is 2 × 7 and 21 is 3 × 7, and in both the 7 is what remains when the divisor loop stops. A copy of the method without the if (rest > 1)
The last line is 1. The number 1 has no prime factors, and 5 and 7 have none in common, so every group holds a single number.
Complexity
The work is filling parent
- Time: O(M + n√M), because filling
touches all M + 1 entries, where M is the largest number, and factoring each of the n numbers tries up to √M divisors.parent - Space: O(M + n), because
has an entry for every value up to M, andparent holds at most one entry per input number.count
Union-find on its own, with a plain list of connections, is the subject of