Largest Divisible Subset solution explained
Largest Divisible Subset asks for the biggest group of numbers, taken from a list of distinct positive integers, in which every pair divides evenly one way or the other. Sort the list first: then a valid group is just a chain where each number divides the next, and a dynamic programming pass with parent pointers finds the longest chain in O(n²). Several groups can tie, and any one of them is a correct answer.
By Evin JohnPublished 8 min read
The problem, in plain terms
You are given a list of different positive whole numbers. Pick as many of them as you can so that, for any two you picked, the bigger one is an exact multiple of the smaller one. Return the numbers you picked, in any order. A single number on its own always qualifies, so the answer is never empty unless the input is.
Case A: [9, 4, 18, 2, 3, 36, 8]
sorted: [2, 3, 4, 8, 9, 18, 36]
chains: 2 -> 4 -> 8 (3)
2 -> 4 -> 36 (3)
3 -> 9 -> 18 -> 36 (4)
answer: [3, 9, 18, 36]
Case B: [5, 7, 11] answer: any one number, e.g. [5]
Case C: [1, 6, 10] answer: [1, 6] or [1, 10]Clarify three things. Are the numbers distinct? (Assume yes; the code still works with repeats, because a number divides itself.) Should you return the subset or its size? (The subset.) If several subsets tie, does it matter which one you return? (Usually any is accepted; ask.) Case C shows why the last question matters.
Why interviewers like it
It hides a familiar DP behind a number theory costume. The skill being tested is the reduction: noticing that a pairwise condition over a whole set collapses to a condition between neighbors once the numbers are sorted. After that it is the longest increasing subsequence template with a different comparison, plus the bookkeeping to return the actual elements rather than a count, which many candidates forget until the end.
Why sorting turns the set into a chain
Take any valid subset and sort it: x1 < x2 < ... < xk. Every pair divides, so in particular each xi divides x(i+1). In the other direction, if each element of a sorted list divides the next, then x1 divides x2 divides x3, and divisibility carries along, so every pair is fine. Valid subsets and divisor chains in sorted order are the same thing. That is the whole reduction, and it is worth saying in those two sentences before writing code.
Brute force: check every subset
Generate all 2^n subsets, test each one pair by pair, and keep the largest that passes. That is O(2^n × n²) and only useful for tiny inputs or as a test oracle. A middle step some candidates propose is recursion over the sorted list, choosing to take or skip each number if it is a multiple of the last one taken; with memoization on (index, last taken) it becomes the DP below.
from itertools import combinations
def largest_divisible_subset_brute(nums):
for size in range(len(nums), 0, -1):
for group in combinations(sorted(nums), size):
if all(group[j] % group[i] == 0
for i in range(size) for j in range(i + 1, size)):
return list(group)
return []Dynamic programming with parent links
Sort ascending. For each position i, size[i] is the length of the longest chain that ends at nums[i]. It starts at 1 (the number alone), and for each earlier j where nums[j] divides nums[i], it can become size[j] + 1. Whenever that improves size[i], record prev[i] = j. Track the index with the largest size. At the end, follow prev links from that index back to the start and reverse.
def largest_divisible_subset(nums):
if not nums:
return []
nums = sorted(nums)
size = [1] * len(nums)
prev = [-1] * len(nums)
best = 0
for i in range(len(nums)):
for j in range(i):
if nums[i] % nums[j] == 0 and size[j] + 1 > size[i]:
size[i] = size[j] + 1
prev[i] = j
if size[i] > size[best]:
best = i
group = []
while best != -1:
group.append(nums[best])
best = prev[best]
return group[::-1]In JavaScript the one trap is the sort. Calling sort() with no comparator orders numbers as strings, so 18 lands before 2 and the chain logic quietly breaks. Always pass a numeric comparator.
function largestDivisibleSubset(input) {
if (input.length === 0) return [];
const nums = [...input].sort((x, y) => x - y);
const size = new Array(nums.length).fill(1);
const prev = new Array(nums.length).fill(-1);
let best = 0;
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < i; j++) {
if (nums[i] % nums[j] === 0 && size[j] + 1 > size[i]) {
size[i] = size[j] + 1;
prev[i] = j;
}
}
if (size[i] > size[best]) best = i;
}
const group = [];
for (let k = best; k !== -1; k = prev[k]) group.push(nums[k]);
return group.reverse();
}Trace Case A on the sorted list [2, 3, 4, 8, 9, 18, 36]. Sizes come out as 1, 1, 2, 3, 2, 3, 4. For 18, the best divisor chain ends at 9 (size 2), so 18 gets size 3 with prev pointing at 9. For 36, both 4 and 18 divide it; 18 has the larger size, so 36 gets size 4 and links to 18. Walking back from 36 gives 36, 18, 9, 3.
Complexity summary
| Approach | Time | Extra memory | Note |
|---|---|---|---|
| Every subset | O(2^n × n²) | O(n) | Test oracle only |
| Sort plus chain DP | O(n²) | O(n) | Expected answer |
| Sort plus chain DP, size only | O(n²) | O(n) | Drop prev if only the count is asked |
Edge cases to try
- Empty list: return an empty list, and do not index size[0].
- One number: return it.
- A 1 in the list: it divides everything, so it joins the best chain for free.
- Only primes: no pair divides, so the answer is any single number.
- Powers of two: every pair divides, so the answer is the whole list.
- Two chains of equal length, like Case C: either is correct, so test by size and validity, not by exact equality.
Mistakes to avoid
- Skipping the sort. Without it the neighbor check does not imply the pairwise rule.
- Sorting numbers as strings in JavaScript.
- Testing divisibility the wrong way round: after an ascending sort, check nums[i] % nums[j], larger by smaller.
- Returning max(size) when the task wants the elements.
- Greedily extending from the smallest number. Starting at 2 in Case A finds a chain of 3 and misses the chain of 4 that starts at 3.
Follow-ups
- Values are small but the list is long. Instead of comparing every earlier element, walk each number's multiples that appear in the list (a sieve-style pass). This trades the n² factor for a bound that depends on the largest value; state that trade rather than claiming a fixed speedup.
- Count the largest subsets. Keep a count next to each size, the same way Number of Longest Increasing Subsequence does.
- Repeated values. The DP still works, since x divides x, but confirm whether duplicates may both be taken.
- Return the smallest-sum or lexicographically first answer among ties. Add a tie-break when updating size[i].
How to explain it out loud
Fictional example
- Candidate
- Checking every pair in a subset sounds expensive, but if I sort the numbers, I only need each one to divide the next. Divisibility carries through the chain.
- Candidate
- So this is a longest chain problem, like longest increasing subsequence, where the comparison is divides instead of less than.
- Interviewer
- And you need the elements back, not just the size.
- Candidate
- Right, so alongside each size I store the index it came from. After the loop I start at the biggest size and follow those links back. O(n squared) time, linear memory.
Related problems
Russian Doll Envelopes is the same sort-then-chain move with two dimensions. Number of Longest Increasing Subsequence adds counting to the chain DP. Longest Arithmetic Subsequence keeps a chain per difference instead of per divisor. For a lighter warm-up on building answers from smaller ones, Climbing Stairs is the simplest recurrence on this site.
Practicing it with Natively
This one rewards a clear two-sentence argument for why sorting is allowed, so practice saying it before you code. Natively works on Mac and Windows: in a practice run it can take the problem from a screenshot and suggest the chain DP, and afterward the transcript shows whether you explained the reduction or jumped straight to loops. The AI assistant for coding interviews page covers those features.
Questions people ask
How do you solve Largest Divisible Subset?
Sort the numbers. For each one, its best chain length is 1 plus the best length of any earlier number that divides it; store which number that was. Start from the longest chain and follow the stored links back to rebuild the subset.
Why does sorting work for Largest Divisible Subset?
In sorted order, if each number divides the next one, every pair divides because divisibility carries along the chain. So a valid subset is exactly a divisor chain in the sorted list.
What is the time complexity of Largest Divisible Subset?
O(n²) time for the double loop after an O(n log n) sort, and O(n) extra memory for the sizes and parent links.
Can there be more than one correct answer?
Yes. Several subsets can share the largest size, and any of them is normally accepted. Test your code by checking the size and the divisibility of every pair, not by comparing to one fixed list.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
