Skip to main content
LeetCode 368, Medium. Topics: Array, Math, Dynamic Programming, Sorting. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:

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.

Examples

Constraints

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 2 * 10^9
  • All the integers in nums are unique.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026