Largest Divisible Subset (LeetCode 368): Solution and Explanation
Given distinct positive integers nums, return the largest subset in which, for every pair, one number divides the other. Any largest subset is accepted; here the hidden tests have a single largest subset and the reference returns it in ascending order.
Intuition
After sorting, a valid subset looks like a chain a1 | a2 | a3 | ..., where each number divides the next. Any two numbers in such a chain divide each other because divisibility is transitive.
So the question becomes: what is the longest chain? That is the longest increasing subsequence problem with "divides" instead of "is smaller than".
For each nums[i], look at every smaller nums[j] that divides it. The best chain ending at nums[i] is the best chain ending at such a nums[j], plus nums[i].
Lengths alone are not enough, since we must return the subset. Storing prev[i] (which j we extended) lets us walk the chain back from its end.
Approach: Sort + O(n^2) chain DP with parent links
- Sort
numsascending. - Set
dp[i] = 1andprev[i] = -1for everyi. - For each
i, for eachj < i: ifnums[i] % nums[j] == 0anddp[j] + 1 > dp[i], setdp[i] = dp[j] + 1andprev[i] = j. - Keep
best, the index with the largestdp. - Walk from
bestthroughprevlinks, collect the numbers, and reverse them.
Step-by-step example
nums = [3, 4, 16, 8, 9, 27, 2]
- Sorted:
[2, 3, 4, 8, 9, 16, 27]. 2and3start chains of size 1.4extends2(size 2).8extends4(size 3).9extends3(size 2).16extends8(size 4).27extends9(size 3).- The best end is
16withdp = 4. Following prev links:16 → 8 → 4 → 2. - Reversed, the answer is
[2, 4, 8, 16].
Code: Python, Java, C++
1class Solution:
2 def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
3 nums.sort()
4 n = len(nums)
5 dp = [1] * n
6 prev = [-1] * n
7 best = 0
8 for i in range(n):
9 for j in range(i):
10 if nums[i] % nums[j] == 0 and dp[j] + 1 > dp[i]:
11 dp[i] = dp[j] + 1
12 prev[i] = j
13 if dp[i] > dp[best]:
14 best = i
15 res = []
16 while best != -1:
17 res.append(nums[best])
18 best = prev[best]
19 return res[::-1]1class Solution {
2 public List<Integer> largestDivisibleSubset(int[] nums) {
3 Arrays.sort(nums);
4 int n = nums.length;
5 int[] dp = new int[n];
6 int[] prev = new int[n];
7 Arrays.fill(dp, 1);
8 Arrays.fill(prev, -1);
9 int best = 0;
10 for (int i = 0; i < n; i++) {
11 for (int j = 0; j < i; j++) {
12 if (nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i]) {
13 dp[i] = dp[j] + 1;
14 prev[i] = j;
15 }
16 }
17 if (dp[i] > dp[best]) {
18 best = i;
19 }
20 }
21 LinkedList<Integer> res = new LinkedList<>();
22 for (int k = best; k != -1; k = prev[k]) {
23 res.addFirst(nums[k]);
24 }
25 return res;
26 }
27}1class Solution {
2public:
3 vector<int> largestDivisibleSubset(vector<int>& nums) {
4 sort(nums.begin(), nums.end());
5 int n = nums.size();
6 vector<int> dp(n, 1), prev(n, -1);
7 int best = 0;
8 for (int i = 0; i < n; i++) {
9 for (int j = 0; j < i; j++) {
10 if (nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i]) {
11 dp[i] = dp[j] + 1;
12 prev[i] = j;
13 }
14 }
15 if (dp[i] > dp[best]) {
16 best = i;
17 }
18 }
19 vector<int> res;
20 for (int k = best; k != -1; k = prev[k]) {
21 res.push_back(nums[k]);
22 }
23 reverse(res.begin(), res.end());
24 return res;
25 }
26};Time and space complexity
O(n^2)
Sorting is O(n log n); the pair loop checks every j < i, about n²/2 pairs.
O(n)
The dp and prev arrays, plus the answer.
Other approaches
Memoized DFS on the sorted array (time O(n^2), space O(n^2) if lists are cached)
Define f(i) as the largest chain starting at nums[i] and recurse into every later multiple. Same O(n^2) work, but recursion depth can reach n and storing whole lists per state costs more memory.
Brute force over subsets (time O(2^n * n^2), space O(n))
Check every subset for pairwise divisibility. Only useful to verify small cases.
Common mistakes
- Forgetting to sort. Without sorting, checking only
nums[i] % nums[j]misses chains where the larger number comes first. - Returning only the size. The problem asks for the subset, so you need
prevlinks (or another way to rebuild it). - Checking every pair in the chain. Thanks to transitivity, checking the new number against the chain end is enough.
- Expecting one specific answer when there are ties, like
[1,2]vs[1,3]for[1,2,3]. LeetCode accepts any largest subset.
Frequently asked questions
Why is checking only the last element of the chain enough?
If a divides b and b divides c, then a divides c. So when nums[j] ends a valid chain and nums[j] divides nums[i], every earlier element also divides nums[i].
Why does sorting make this an LIS problem?
In a valid subset, a smaller number can only divide a larger one. After sorting, every valid subset appears as a subsequence where each element divides the next, which is exactly an LIS with a different comparison.
What if several subsets have the same largest size?
Any of them is correct on LeetCode. This judge uses tests where the largest subset is unique, so the comparison is unambiguous, and accepts the elements in any order.