Largest Divisible Subset

Find the biggest group of numbers in which, for every pair, the larger one divides evenly by the smaller.

Given an array nums of distinct positive integers, return the largest subset in which every pair divides evenly. That means for any two numbers a and b in it, a % b == 0 or b % a == 0. A subset is any selection of the numbers. If several subsets share the largest size, any of them is accepted.

Example 1
Input: nums = [1, 2, 3]
Output: [1, 2]
Explanation: [1, 3] is also accepted.
Example 2
Input: nums = [1, 2, 4, 8]
Output: [1, 2, 4, 8]
Solution

The Idea

Take the numbers 1, 2, 4 and 8 from Example 2. Pick any two of them, and the bigger one is a whole number of times the smaller: 8 is 2 times 4, 8 is 4 times 2, 4 is 4 times 1, and so on. The bigger one divides evenly by the smaller, with remainder 0, which is what a % b == 0 checks.

Example 1 is different. The numbers 2 and 3 cannot both be in the subset, because 3 divided by 2 leaves 1 over. Each of them does go with 1, so the best we can do is two numbers: [1, 2] or [1, 3].

Now take nums = [1, 2, 3, 4, 8]. Which numbers belong together? Five numbers have 32 subsets, and checking every pair inside every one of them is a lot of work. Is there a way to grow a good subset one number at a time?

Write the numbers smallest first and look at 1, 2, 4, 8 in that order. Each number divides evenly by the one before it: 2 by 1, 4 by 2, 8 by 4. That is enough for every pair. Because 4 is 2 times 2 and 8 is 2 times 4, 8 is 2 times 2 times 2, so 8 divides evenly by 2 as well.

Call a list like this, where each number divides evenly by the one before it, a chain. Every valid subset, sorted, is a chain, and every chain is a valid subset. So a new number can join the end of a chain when it divides evenly by the chain's last number, its largest. That turns the question around: for each number, what is the longest chain that ends with it? Look at the picture below.

The sorted numbers 1, 2, 3, 4, 8. Under each one, the longest chain ending here is 1, 2, 2, 3, 4, and the number before it is none, 1, 1, 2, 4. Following the number before it back from 8 gives 8, 4, 2, 1. The chain 1, 3 goes no further.

The row labelled "longest chain ending here" fills in from left to right. The number 1 stands alone, so its chain has length 1. Next, 2 divides evenly by 1, so it joins the chain of 1 and gets length 2, and 3 does the same. Then 4 divides evenly by 1 and by 2. The chain of 2 is longer, so 4 joins it and gets 3. Last, 8 divides evenly by 1, 2 and 4, and joins the chain of 4, the longest of the three, for length 4.

The row labelled "number before it" records which chain each number joined. To get the subset, start at the largest length, 4 under the number 8, and follow "number before it" back: 8, 4, 2, 1. The dashed arrow is the chain 1, 3, which stops at length 2 because no later number is a multiple of 3.

Working out the length under 8 from the lengths already written under 1, 2 and 4, instead of searching for chains all over again, is called dynamic programming. Each length in the row labelled "longest chain ending here" is built from lengths to its left.

Solution Approach

Turning that idea into code means settling four things: why trying every subset is slow, why the numbers are sorted first, how each number's chain length is found, and how the subset is rebuilt from those lengths.

Trying every subset

Why not list every subset and keep the largest valid one? Each number is either in or out, so n numbers have 2n subsets: 32 for the five numbers in the picture, but over a billion for 30 numbers. Each subset then needs all its pairs checked. Chain lengths need one remainder check per pair of positions instead.

Sorting the numbers first

Why sort? A chain is read smallest first, and a positive number can only divide evenly by numbers no bigger than itself. Once nums is sorted, every number that could come before nums[i] in a chain sits to its left, at some position j smaller than i. So the search for each number only has to look left.

The longest chain ending at each number

How is the length under each number found? Call it size[i]: the length of the longest chain that ends with nums[i]. It starts at 1, for nums[i] on its own. For every position j to the left with nums[i] % nums[j] == 0, the chain ending with nums[j] can take nums[i] on its end, for a length of size[j] + 1. In the end, size[i] keeps the largest of these lengths.

The page on Longest Increasing Subsequence works out a length for each number the same way, with "is smaller than" where this one has "divides evenly".

Rebuilding the subset

The answer is the subset itself, not its length, so how do we get the numbers back? A second array, prev, stores for each i the position of the number before nums[i] in its longest chain, or -1 when nums[i] starts the chain. The picture shows the number itself; the code keeps its position, which leads straight to the next entry to read.

A variable bestEnd holds the position with the largest size seen so far. It moves only when a strictly larger length appears, so on a tie the earlier chain wins: in Example 1, 2 and 3 both have length 2, and the answer is [1, 2]. Following prev from bestEnd until it reaches -1 visits the subset from its largest number down to its smallest.

Java Solution

The method largestDivisibleSubset works in these steps:

  1. First, sort the input array with Arrays.sort(nums), so every number that can come before another in a chain sits to its left.
  2. Create two arrays of length n, the number of values: size for the longest chain ending at each position, and prev for the position before it in that chain. Set bestEnd to 0.
  3. Visit each position with a loop over i. Start size[i] at 1 and prev[i] at -1. Inside, a second loop moves j over every position before i. When nums[i] % nums[j] == 0 and size[j] + 1 is bigger than size[i], set size[i] to size[j] + 1 and prev[i] to j.
  4. After the second loop, if size[i] is larger than size[bestEnd], move bestEnd to i.
  5. Finally, build the list subset: start at bestEnd and follow prev until -1, adding each number at the front with subset.add(0, ...), so the subset comes out smallest first.

A small helper, run, prints an input array, an arrow and the subset found for it. The main method uses it on both examples, the five numbers from the picture, an unsorted array holding two chains, numbers where none divides another, a single number, and an array whose order it prints again after the call.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LargestDivisibleSubset {

    public static List<Integer> largestDivisibleSubset(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        int[] size = new int[n];   // length of the longest chain that ends with nums[i]
        int[] prev = new int[n];   // position of the number before nums[i] in that chain
        int bestEnd = 0;
        for (int i = 0; i < n; i++) {
            size[i] = 1;           // nums[i] on its own
            prev[i] = -1;
            for (int j = 0; j < i; j++) {
                if (nums[i] % nums[j] == 0 && size[j] + 1 > size[i]) {
                    size[i] = size[j] + 1;   // extend the chain that ends with nums[j]
                    prev[i] = j;
                }
            }
            if (size[i] > size[bestEnd]) {
                bestEnd = i;
            }
        }
        List<Integer> subset = new ArrayList<>();
        for (int i = bestEnd; i != -1; i = prev[i]) {
            subset.add(0, nums[i]);  // walk the chain back to its start
        }
        return subset;
    }

    static void run(int[] nums) {
        String input = Arrays.toString(nums);
        List<Integer> subset = largestDivisibleSubset(nums);
        System.out.println(input + " -> " + subset);
    }

    public static void main(String[] args) {
        run(new int[] {1, 2, 3});
        run(new int[] {1, 2, 4, 8});
        run(new int[] {1, 2, 3, 4, 8});
        run(new int[] {3, 4, 16, 8, 9, 27, 81});
        run(new int[] {2, 3, 5, 7});
        run(new int[] {7});
        int[] nums = {8, 4, 1, 2};
        run(nums);
        System.out.println("nums afterwards: " + Arrays.toString(nums));
    }
}

Running it prints:

Output
[1, 2, 3] -> [1, 2]
[1, 2, 4, 8] -> [1, 2, 4, 8]
[1, 2, 3, 4, 8] -> [1, 2, 4, 8]
[3, 4, 16, 8, 9, 27, 81] -> [3, 9, 27, 81]
[2, 3, 5, 7] -> [2]
[7] -> [7]
[8, 4, 1, 2] -> [1, 2, 4, 8]
nums afterwards: [1, 2, 4, 8]

Example 1 comes out as [1, 2], the earlier of the two tied chains. The third line, [1, 2, 3, 4, 8], is the array from the picture, and its answer [1, 2, 4, 8] is the chain traced back from 8. In the fourth line, the input holds two chains, 4, 8, 16 and 3, 9, 27, 81, and the longer one wins even though its numbers were scattered through the input.

In [2, 3, 5, 7] no number divides evenly by another, so every length stays 1 and bestEnd never leaves position 0, which gives [2]. A single number such as [7] is a valid subset on its own.

Look at the last two lines. The call was given [8, 4, 1, 2], and afterwards nums reads [1, 2, 4, 8], because Arrays.sort sorts the caller's array in place. Pass nums.clone() instead if the original order matters.

Leaving the sort out is not an option either. With the Arrays.sort line removed, [4, 2, 1] gives [4] and [8, 4, 1, 2] gives [1, 2]. In [4, 2, 1], 4 sits left of 2 and 1, so neither of them can join its chain, and it cannot join theirs.

Complexity

The work is the sort, plus one remainder check for every pair of positions in the two loops.

  • Time: O(n²), because for each of the n numbers the inner loop checks every number to its left, about n²/2 remainder checks in all. The sort takes O(n log n), and rebuilding the subset with add(0, ...) shifts at most n numbers per step, so neither adds more than O(n²).
  • Space: O(n), because size and prev hold one entry per number, and the subset holds at most n numbers.