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 of distinct positive integers, draw a line between two numbers whenever they have a common factor greater than 1, that is, some number greater than 1 divides both of them. Numbers that can reach each other by following lines form one group, called a connected component. Return how many numbers the largest group holds.

Example 1
Input: nums = [4, 6, 15, 35]
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
Input: nums = [20, 50, 9, 63]
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.
Solution

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 input numbers 4, 6, 15 and 35 in a top row and the prime factors 2, 3, 5 and 7 in a bottom row, with a line from each number to each of its prime factors. 6 and 15 both join 3, so all four numbers land in one group.

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, max, an entry in an array named parent. A prime such as 7 and a number such as 35 then both have a place, and since the input numbers are distinct, no two of them share an entry.

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] = 2, and joining 6 with 2 sets parent[6] = 2, so 4 and 6 now have the same root, 2. Joining 6 with 3 finds the root of 6, which is 2, and sets parent[2] = 3. Now 4 and 6 both lead up to the root 3.

The chains of parents can grow long. So while the method that finds a root, named find, walks up, it points each value it passes at its grandparent, the parent of its parent, and later walks take fewer steps.

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 rest. If rest still had two prime factors, both at least f, their product would be at least f × f. So a rest left above 1 is itself a prime, and it must be joined too. For 35, f = 5 divides it and leaves rest = 7. The next f, 6, gives 6 × 6 = 36, which is more than 7, so the loop stops and 7 is that leftover prime.

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 works in these steps:

  1. First, find the largest number, max, and create parent with max + 1 entries, setting each value as its own parent.
  2. Go through the numbers with a loop. For each number x, copy it into rest, and inside, a second loop tries divisors f from 2 while f * f <= rest. When f divides rest, the helper union joins x with f, and every copy of f is divided out of rest.
  3. After the divisor loop, if rest > 1, join x with rest, the leftover prime.
  4. Then create a map named count, from root to the number of input numbers with that root. For each x, the helper find gives its root, count.merge adds one for that root, and best keeps the largest count seen.
  5. When every number is counted, return best.

The main method runs both examples and eight numbers linked through the primes 2, 3, 7 and 13. It also tries 14 and 21, whose shared prime is a leftover, and [1, 5, 7], where no two numbers share a factor.

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

Output
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]: 39 is 3 × 13 and joins the rest through 3. Here 2, 3 and 7 are input numbers and also prime factors of other numbers, and each uses one entry of parent in both roles.

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) step prints 1 here. It also prints 2 instead of 4 for Example 1, because 6 then loses its link to 3 and 15 its link to 5.

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, factoring each number by trial division, and a few joins and finds per number.

  • Time: O(M + n√M), because filling parent touches all M + 1 entries, where M is the largest number, and factoring each of the n numbers tries up to √M divisors.
  • Space: O(M + n), because parent has an entry for every value up to M, and count holds at most one entry per input number.

Union-find on its own, with a plain list of connections, is the subject of Number of Connected Components.