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 INPUT nums array (unsorted) 1 2 3 6 [0] [1] [2] [3] Divisibility Graph: 1 2 3 6 1 divides all, 6 divisible by 2,3 nums = [1,2,3,6] ALGORITHM STEPS 1 Sort Array [1,2,3,6] (already sorted) 2 Init DP Arrays dp[i]=1, parent[i]=-1 3 Build DP Table If nums[i]%nums[j]==0 idx: 0 1 2 3 nums: 1 2 3 6 dp: 1 2 2 3 parent: -1 0 0 1 max=3 at idx=3 4 Backtrack 6-->2-->1 via parents idx 3-->1-->0-->done result: [1,2,6] FINAL RESULT Largest Divisible Subset 1 --> 2 --> 6 Verification: 2 % 1 == 0 OK 6 % 1 == 0 OK 6 % 2 == 0 OK All pairs valid! Output: [1, 2, 6] Subset Size: 3 Key Insight: After sorting, if a divides b and b divides c, then a divides c (transitivity). Use DP: dp[i] = longest subset ending at nums[i]. For each i, check all j < i where nums[i] % nums[j] == 0. Time: O(n^2) | Space: O(n) for dp and parent arrays TutorialsPoint - Largest Divisible Subset | Optimal 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