Largest Divisible Subset - Problem

You're given a set of distinct positive integers, and your task is to find the largest subset where every pair of elements has a special divisibility property.

Specifically, for any two elements a and b in your chosen subset, either:

  • a % b == 0 (a is divisible by b), OR
  • b % a == 0 (b is divisible by a)

This means that in a valid subset, you can always arrange the numbers in a sequence where each number divides the next one. For example, [1, 2, 4, 8] works because 1|2, 2|4, and 4|8.

Goal: Return the largest such subset. If multiple subsets have the same maximum size, return any one of them.

Example: Given [1, 2, 3, 4, 6], the answer could be [1, 2, 4] or [1, 2, 6] or [1, 3, 6] - all have length 3.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1, 2, 3, 4, 6]
โ€บ Output: [1, 2, 4] or [1, 2, 6] or [1, 3, 6]
๐Ÿ’ก Note: Multiple valid subsets exist with length 3. In [1,2,4]: 1|2, 2|4. In [1,2,6]: 1|2, 2|6. In [1,3,6]: 1|3, 3|6.
example_2.py โ€” Perfect Chain
$ Input: [1, 2, 4, 8]
โ€บ Output: [1, 2, 4, 8]
๐Ÿ’ก Note: This forms a perfect divisible chain where each element divides the next: 1|2, 2|4, 4|8. The entire array is the answer.
example_3.py โ€” Single Element
$ Input: [1]
โ€บ Output: [1]
๐Ÿ’ก Note: With only one element, that element itself forms the largest (and only) divisible subset.

Visualization

Tap to expand
Building the Tallest Divisible TowerInput blocks: [1, 2, 3, 4, 6, 8, 12]Step 1: Sort blocks by size12346812Step 2: Find best tower for each block1248Tower 1: [1,2,4,8]Height: 413612Tower 2: [1,3,6,12]Height: 4Step 3: Choose the tallest towerBoth towers have height 4, so we can return either:Result: [1, 2, 4, 8] or [1, 3, 6, 12]๐Ÿ’ก Key Insight: After sorting, a divisible subset forms a chain where each element divides the next!
Understanding the Visualization
1
Sort the Blocks
Arrange all blocks by size to make stacking decisions easier
2
Try Each Position
For each block, find the tallest valid tower it can extend
3
Build the Tower
Use the best combination to build the tallest possible tower
Key Takeaway
๐ŸŽฏ Key Insight: The secret is recognizing that after sorting, any valid divisible subset forms a chain where smaller numbers divide larger ones, making DP transitions straightforward.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ)

O(n log n) for sorting + O(nยฒ) for DP transitions

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Space for DP array, parent array, and result

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • 1 โ‰ค nums[i] โ‰ค 2 ร— 109
  • All integers in nums are distinct
  • You may return the answer in any order
Asked in
Google 45 Amazon 32 Microsoft 28 Meta 22
89.3K Views
Medium-High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen