Leetcode #368: Largest Divisible Subset
In this guide, we solve Leetcode #368 Largest Divisible Subset in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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. Example 1: Input: nums = [1,2,3] Output: [1,2] Explanation: [1,3] is also accepted.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Math, Dynamic Programming, Sorting
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: nums = [1,2,3]
Output: [1,2]
Explanation: [1,3] is also accepted.
Python Solution
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
nums.sort()
n = len(nums)
f = [1] * n
k = 0
for i in range(n):
for j in range(i):
if nums[i] % nums[j] == 0:
f[i] = max(f[i], f[j] + 1)
if f[k] < f[i]:
k = i
m = f[k]
i = k
ans = []
while m:
if nums[k] % nums[i] == 0 and f[i] == m:
ans.append(nums[i])
k, m = i, m - 1
i -= 1
return ans
Complexity
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.