LeetCode #368 Medium

Largest Divisible Subset

Largest Divisible Subset is LeetCode 368 (Medium). You get an array nums of distinct positive integers. Return the largest subset in which every pair (a, b) satisfies a % b == 0 or b % a == 0. If several subsets have the same size, any of them is accepted.

  • There are at most 1,000 numbers, so checking every pair (about 500,000 checks) is fine.
  • Trying every subset is not: 1,000 numbers have 2¹⁰⁰⁰ subsets.
Constraints
  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 2 * 10⁹
  • All the integers in nums are unique.
dynamic-programmingmathsorting
Open on LeetCode ↗
02

Intuition

Sort the numbers. In sorted order, a valid subset is a chain where each number divides the next one, like 1 → 2 → 4 → 8.

  • Why a chain is enough: division carries through. If 2 divides 4 and 4 divides 8, then 2 divides 8. So checking neighbours in the chain covers every pair.
  • Why every valid subset is a chain: in a valid subset, the smaller of any two numbers divides the larger, so each number divides the next one in sorted order.

That turns the problem into "find the longest chain", the same shape as Longest Increasing Subsequence with "divides" in place of "is smaller than".

How to spot this pattern

A pairwise rule that carries through (if a relates to b and b to c, then a relates to c), plus a request for the biggest group, points to sorting and then a longest-chain DP. Remember each element’s predecessor whenever the group itself, not just its size, must be returned.

03

Approach

Try it first

Before reading on, sort [9, 2, 4, 3, 8] and write, for each number, the longest chain that ends at it. Which number ends the longest chain, and is it the largest one?

1

Sort the numbers

Sort nums in ascending order. A smaller number can divide a bigger one but never the reverse, so after sorting each number only needs to be tested against the numbers before it, with nums[i] % nums[j] == 0.

2

Store the best chain ending at each number

Let dp[i] be the length of the longest chain whose last number is nums[i], and parent[i] the index of the number just before it. Every number starts as a chain of length 1 with no parent, because a number on its own is a valid subset.

3

Try every earlier divisor

For each i, look at every j < i. If nums[j] divides nums[i] and dp[j] + 1 > dp[i], set dp[i] = dp[j] + 1 and parent[i] = j. Adding nums[i] after nums[j] is safe, since nums[j] divides nums[i] and so does everything before nums[j] in that chain.

4

Track where the longest chain ends

Keep the index whose dp is largest while you fill the table. The longest chain can end before the largest number: in [2, 3, 4, 8, 9] it ends at 8, not 9.

5

Rebuild the subset

Start at the best index and follow parent links until one is -1, collecting each number. The numbers come out from largest to smallest, so reverse them before returning (any order is accepted, but sorted reads best).

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def largestDivisibleSubset(self, nums):
▶3 nums.sort()
▶4 n = len(nums)
▶5 dp = [1] * n
▶6 parent = [-1] * n
▶7 best_idx = 0
▶8 for i in range(1, 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 parent[i] = j
▶13 if dp[i] > dp[best_idx]:
▶14 best_idx = i
▶15 result = []
▶16 idx = best_idx
▶17 while idx != -1:
▶18 result.append(nums[idx])
▶19 idx = parent[idx]
▶20 return result[::-1]
sorted numbers, arrow from the best divisor1chain 12chain 13chain 1divisibility checksort → a divisor always comes before its multiples
sorted[1, 2, 3]
A smaller number can divide a bigger one, never the other way round. After sorting, each number only needs to be checked against the numbers to its left. Every number starts as a chain of length 1 on its own.
sorted numbers, arrow from the best divisor1chain 12chain 23chain 1does 1 divide 2?2÷1=2no remainder2>1newhadextend the chain at 1 → length 2
pair1 → 2
chain at 22
1 divides 2, and it divides everything earlier in its own chain too (division carries through). So 2 can join that chain, making it 2 long. Remember 1 as the number before it.
sorted numbers, arrow from the best divisor1chain 12chain 23chain 2does 1 divide 3?3÷1=3no remainder2>1newhadextend the chain at 1 → length 2
pair1 → 3
chain at 32
1 divides 3, and it divides everything earlier in its own chain too (division carries through). So 3 can join that chain, making it 2 long. Remember 1 as the number before it.
sorted numbers, arrow from the best divisor1chain 12chain 23chain 2does 2 divide 3?3÷2=1 r 1remainder2 does not divide 3 → skip
pair2 → 3
chain at 32
3 is not a multiple of 2, so 3 cannot follow 2 in a chain.
sorted numbers, arrow from the best divisor1chain 12chain 23chain 2divisibility checklongest chain ends at 2 (length 2)
best end2chain 2
The longest chain ends at 2, not at the largest number 3. That is why the code tracks the best end while it fills the table.
sorted numbers, arrow from the best divisor1chain 12chain 23chain 2subset, rebuilt from its largest number2take 2, then follow its arrow back
subset[2]
Take 2. Its arrow points back to 1, the number it was chained after.
sorted numbers, arrow from the best divisor1chain 12chain 23chain 2subset, rebuilt from its largest number12take 1: no arrow, chain starts here
subset[1, 2]
1 has no arrow, so it is the start of the chain. The subset is complete.
sorted numbers, arrow from the best divisor1chain 12chain 23chain 2subset, rebuilt from its largest number12answer: 1, 2
answer[1, 2]2 numbers
Each number in 1, 2 divides the next one, and division carries through, so every pair divides one way. No larger subset exists, because no chain is longer than 2.
05

Common pitfalls

Testing divisibility the wrong way round

✗ Wrong
if nums[j] % nums[i] == 0:
✓ Right
if nums[i] % nums[j] == 0:

After sorting, nums[j] is the smaller number, and a smaller positive number is never a multiple of a bigger one. On [1, 2, 4, 8] no chain ever grows, and the function returns [1] instead of [1, 2, 4, 8].

Skipping the sort

✗ Wrong
dp = [1] * n  # nums used as given
✓ Right
nums.sort()
dp = [1] * n

The loop only looks left for divisors. On [4, 2, 1] every divisor sits to the right of its multiple, so nothing is chained and the answer is [4] instead of [1, 2, 4].

Assuming the chain ends at the last number

✗ Wrong
idx = n - 1
✓ Right
if dp[i] > dp[best_idx]:
    best_idx = i

On [1, 2, 4, 7] the last number 7 only ends the chain [1, 7], while [1, 2, 4] is longer. Starting the rebuild at the last index returns the shorter subset.

06

Edge cases

No number divides another, e.g. [2, 3, 5]

Every dp value stays 1 and the best index stays 0, so the answer is [2]. Any single number is a correct answer.

A single number, e.g. [7]

The loops do not run, and the rebuild returns [7].

07

Complexity

Time
O(n²)
Space
O(n)
Sorting costs O(n log n). The double loop checks each pair (j, i) once, about n²/2 checks, which dominates. The rebuild walks at most n parent links. The dp and parent arrays hold n values each.
08

Largest Divisible Subset FAQ

If 1 is in the array, is it always in the answer?

It can always be added. 1 divides every number, so putting it at the start of any chain keeps the subset valid and makes it one longer. The code needs no special case: a longest chain that skipped 1 could be made longer by adding it, so the chain the code finds always starts at 1.

Can the O(n log n) trick for increasing subsequences be used here?

No. That trick keeps one best tail per chain length and binary searches it, which relies on "smaller than" ordering all numbers in one line. "Divides" does not: 4 and 6 are neither divisor nor multiple of each other. So the pair-by-pair O(n²) DP is the standard solution.