Skip to main content
Back to problems
Leetcode
Medium
Arrays
Dynamic Programming
Sorting
Number Theory
Largest Divisible Subset

Find the largest subset of numbers such that every pair is divisible in at least one direction after ordering the subset appropriately.

Acceptance 0%
Problem Statement

Given a list of distinct positive integers, return the largest subset such that for every pair of elements in the subset, one number divides the other. If multiple valid subsets have the same maximum size, any one of them may be returned.

A common way to think about the condition is to arrange the chosen numbers in increasing order, where each number divides the next number in the sequence.

Input Format

  • An integer array nums of distinct positive integers.
  • nums[i] represents one candidate number that may be included in the subset.

Output Format

  • Return the largest divisible subset as an array of integers.
  • The order of returned elements should be increasing or otherwise consistent with divisibility.

Constraints

  • 1 <= nums.length
  • nums[i] > 0
  • All values in nums are distinct.
  • The subset must be non-empty.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,2,3]

Output

[1,2]

Explanation

Both [1,2] and [1,3] are valid largest subsets of size 2.

Example 2

Input

nums = [1,2,4,8]

Output

[1,2,4,8]

Explanation

Each number divides the next one, so the whole array is a valid subset.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.