Skip to content
Problem 368 · LeetCode 368(opens in a new tab)

Largest Divisible Subset

MediumDynamic programming

You are given a list nums of distinct positive whole numbers. Pick as many of them as you can so that, for any two numbers you picked, the larger one is a multiple of the smaller one.

Return the numbers you picked, in any order. If several picks have the same largest size, any one of them is accepted.

Example 1

Input:  nums = [10, 5, 3, 20, 4]
Output: [5, 10, 20]
Why:    10 = 2 · 5 and 20 = 2 · 10; no four numbers work
2 more examples and the constraints

Example 2

Input:  nums = [7]
Output: [7]
Why:    a single number always works

Example 3

Input:  nums = [2, 8, 32, 4]
Output: [2, 4, 8, 32]
Why:    each number is a multiple of every smaller one

Constraints

  • 1 ≤ length of nums ≤ 1,000
  • 1 ≤ nums[i] ≤ 2,000,000,000
  • All numbers are different

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort + recursion with memoO(n²)
  2. Sort + DP with parent pointersO(n²)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 numbersVerdict
Sort + recursion with memoO(n²)
Passes; recursion overhead
Sort + DP with parent pointersO(n²)
Best; two plain loops

n = how many numbers there are. Trying every subset would be 2ⁿ.

Edge cases to test

  • One number. [7] is its own answer.
  • The number 1. 1 divides everything, so it can join any chain: [1, 6, 12, 35] gives [1, 6, 12].
  • A divisor that does not chain. In [4, 8, 10, 240], both 8 and 10 divide 240, but 4 does not divide 10. The answer is [4, 8, 240].
  • Large values. 2,000,000,000 still fits in a 32-bit int, and only % is used, so nothing overflows.

Common mistakes

  • Forgetting to sort, so a number's divisors can come after it.
  • Keeping only the sizes and losing the chain: you need prev to return the numbers.
  • Walking back from the last index instead of the index with the largest size.

How to talk through it

  1. 1Clarify. Are the numbers distinct and positive? Can I return any of several best answers, in any order?
  2. 2Spot the chain. Divisibility is transitive, so after sorting a valid pick is a chain where each number divides the next.
  3. 3Map it to LIS. size[i] is the best chain ending at i; it extends any earlier divisor's chain.
  4. 4Rebuild the answer. Store prev[i] and walk it back from the best end. O(n²) time, O(n) space.
  5. 5Test out loud. Run a single number, a list with 1, and the case where two divisors of one number do not divide each other.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?