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 numsa % b == 0b % a == 0
Example 1
Output: [1, 2]
Explanation: [1, 3] is also accepted.
Example 2
Output: [1, 2, 4, 8]
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
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]
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 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 numsnums[i]
The longest chain ending at each number
How is the length under each number found? Call it size[i]nums[i]nums[i]nums[i] % nums[j] == 0nums[j]nums[i]size[j] + 1size[i]
The page on
Rebuilding the subset
The answer is the subset itself, not its length, so how do we get the numbers back? A second array, prevnums[i]nums[i]
A variable bestEndsizeprevbestEnd
Java Solution
The method largestDivisibleSubset
- First, sort the input array with
, so every number that can come before another in a chain sits to its left.Arrays.sort(nums) - Create two arrays of length
, the number of values:n for the longest chain ending at each position, andsize for the position before it in that chain. Setprev to 0.bestEnd - Visit each position with a loop over
. Starti at 1 andsize[i] at -1. Inside, a second loop movesprev[i] over every position beforej . Wheni andnums[i] % nums[j] == 0 is bigger thansize[j] + 1 , setsize[i] tosize[i] andsize[j] + 1 toprev[i] .j - After the second loop, if
is larger thansize[i] , movesize[bestEnd] tobestEnd .i - Finally, build the list
: start atsubset and followbestEnd until -1, adding each number at the front withprev , so the subset comes out smallest first.subset.add(0, ...)
A small helper, runmain
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:
[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
Look at the last two lines. The call was given [8, 4, 1, 2], and afterwards numsArrays.sortnums.clone()
Leaving the sort out is not an option either. With the Arrays.sort
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
shifts at most n numbers per step, so neither adds more than O(n²).add(0, ...) - Space: O(n), because
andsize hold one entry per number, and the subset holds at most n numbers.prev