Largest Divisible Subset - Problem

Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:

  • answer[i] % answer[j] == 0, or
  • answer[j] % answer[i] == 0

If there are multiple solutions, return any of them.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,6]
Output: [1,2,6]
💡 Note: Clear step-by-step: 1 divides 2 (2%1=0), 2 divides 6 (6%2=0), and 1 divides 6 (6%1=0). All pairs satisfy divisibility.
Example 2 — Alternative Chain
$ Input: nums = [1,2,4,8]
Output: [1,2,4,8]
💡 Note: Perfect chain where each number divides the next: 1|2, 2|4, 4|8. All pairs are divisible.
Example 3 — Single Element
$ Input: nums = [5]
Output: [5]
💡 Note: With only one element, it forms a valid divisible subset by itself.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 2 × 109
  • All the integers in nums are unique

Visualization

Tap to expand
Largest Divisible Subset ProblemInput Array:1236Find subset where every pair satisfies:nums[i] % nums[j] == 0 OR nums[j] % nums[i] == 0Valid Subset:126Output: [1,2,6] - Length 3
Understanding the Visualization
1
Input
Array of distinct positive integers
2
Process
Find subset where every pair is divisible
3
Output
Largest valid divisible subset
Key Takeaway
🎯 Key Insight: Divisibility has transitivity property - if a|b and b|c, then a|c, allowing efficient DP solution
Asked in
Google 25 Facebook 20 Amazon 15
28.5K Views
Medium Frequency
~25 min Avg. Time
982 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