KatInterview

368. Largest Divisible Subset

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the largest subset from a given set of distinct positive integers nums such that for any two numbers a and b in the subset, either a is divisible by b or b is divisible by a. This property is called mutual divisibility.

Solution

Largest Divisible Subset in Python

class Solution:
    def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
        n = len(nums)
        if n == 0:
            return []

        # 1. Sort the array to ensure that for any pair (nums[j], nums[i]) with j < i,
        # if a divisible relationship exists, it must be nums[i] % nums[j] == 0.
        nums.sort()

        # 2. Initialize DP arrays.
        # dp[i] will store the size of the largest divisible subset ending with nums[i].
        dp = [1] * n
        # prev[i] will store the index of the previous element.
        prev = [-1] * n

        # Variables to track the end of the largest subset found so far.
        max_len = 1
        max_idx = 0

        # 3. Fill DP table.
        for i in range(n):
            for j in range(i):
                # If nums[i] is divisible by nums[j], we can potentially extend the subset ending at j.
                if nums[i] % nums[j] == 0:
                    # If extending the subset from j results in a longer subset for i.
                    if dp[j] + 1 > dp[i]:
                        dp[i] = dp[j] + 1
                        prev[i] = j
            
            # Update the overall maximum length and the index of its last element.
            if dp[i] > max_len:
                max_len = dp[i]
                max_idx = i

        # 4. Reconstruct the path of the largest divisible subset.
        result = []
        current_idx = max_idx
        while current_idx != -1:
            result.append(nums[current_idx])
            current_idx = prev[current_idx]

        # The result is constructed in reverse order. Reverse it to get ascending order,
        # which matches the examples.
        return result[::-1]

Largest Divisible Subset in Java

class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        int n = nums.length;
        if (n == 0) {
            return new ArrayList<>();
        }

        // 1. Sort the array to ensure that for any pair (nums[j], nums[i]) with j < i,
        // if a divisible relationship exists, it must be nums[i] % nums[j] == 0.
        Arrays.sort(nums);

        // 2. Initialize DP arrays.
        // dp[i] will store the size of the largest divisible subset ending with nums[i].
        int[] dp = new int[n];
        Arrays.fill(dp, 1);
        // prev[i] will store the index of the previous element in the LIS ending at nums[i].
        int[] prev = new int[n];
        Arrays.fill(prev, -1);

        // Variables to track the end of the largest subset found so far.
        int maxLen = 1;
        int maxIdx = 0;

        // 3. Fill DP table.
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                // If nums[i] is divisible by nums[j], we can potentially extend the subset ending at j.
                if (nums[i] % nums[j] == 0) {
                    // If extending the subset from j results in a longer subset for i.
                    if (dp[j] + 1 > dp[i]) {
                        dp[i] = dp[j] + 1;
                        prev[i] = j;
                    }
                }
            }
            // Update the overall maximum length and the index of its last element.
            if (dp[i] > maxLen) {
                maxLen = dp[i];
                maxIdx = i;
            }
        }

        // 4. Reconstruct the path of the largest divisible subset.
        List<Integer> result = new ArrayList<>();
        int currentIdx = maxIdx;
        while (currentIdx != -1) {
            result.add(nums[currentIdx]);
            currentIdx = prev[currentIdx];
        }

        // The result is constructed in reverse order. The problem doesn't mandate a specific order,
        // but examples suggest sorted order. Reversing provides a sorted (ascending) subset.
        Collections.reverse(result);
        return result;
    }
}

Largest Divisible Subset in C++

class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int>& nums) {
        int n = nums.size();
        if (n == 0) {
            return {};
        }

        // 1. Sort the array to ensure that for any pair (nums[j], nums[i]) with j < i,
        // if a divisible relationship exists, it must be nums[i] % nums[j] == 0.
        sort(nums.begin(), nums.end());

        // 2. Initialize DP arrays.
        // dp[i] will store the size of the largest divisible subset ending with nums[i].
        vector<int> dp(n, 1);
        // prev[i] will store the index of the previous element in the largest divisible subset ending with nums[i].
        vector<int> prev(n, -1);

        // Variables to track the end of the largest subset found so far.
        int max_len = 1;
        int max_idx = 0;

        // 3. Fill DP table.
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < i; ++j) {
                // If nums[i] is divisible by nums[j], we can potentially extend the subset ending at j.
                if (nums[i] % nums[j] == 0) {
                    // If extending the subset from j results in a longer subset for i.
                    if (dp[j] + 1 > dp[i]) {
                        dp[i] = dp[j] + 1;
                        prev[i] = j;
                    }
                }
            }
            // Update the overall maximum length and the index of its last element.
            if (dp[i] > max_len) {
                max_len = dp[i];
                max_idx = i;
            }
        }

        // 4. Reconstruct the path of the largest divisible subset.
        vector<int> result;
        int current_idx = max_idx;
        while (current_idx != -1) {
            result.push_back(nums[current_idx]);
            current_idx = prev[current_idx];
        }
        
        // The result is constructed in reverse order. The problem doesn't mandate a specific order,
        // but examples suggest sorted order. Reversing provides a sorted (ascending) subset.
        reverse(result.begin(), result.end());
        return result;
    }
};

Largest Divisible Subset in TypeScript

function largestDivisibleSubset(nums: number[]): number[] {
    const n = nums.length;
    if (n === 0) {
        return [];
    }

    // 1. Sort the array to ensure that for any pair (nums[j], nums[i]) with j < i,
    // if a divisible relationship exists, it must be nums[i] % nums[j] == 0.
    nums.sort((a, b) => a - b);

    // 2. Initialize DP arrays.
    // dp[i] will store the size of the largest divisible subset ending with nums[i].
    const dp: number[] = new Array(n).fill(1);
    // prev[i] will store the index of the previous element.
    const prev: number[] = new Array(n).fill(-1);

    // Variables to track the end of the largest subset found so far.
    let maxLen = 1;
    let maxIdx = 0;

    // 3. Fill DP table.
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < i; j++) {
            // If nums[i] is divisible by nums[j], we can potentially extend the subset ending at j.
            if (nums[i] % nums[j] === 0) {
                // If extending the subset from j results in a longer subset for i.
                if (dp[j] + 1 > dp[i]) {
                    dp[i] = dp[j] + 1;
                    prev[i] = j;
                }
            }
        }
        // Update the overall maximum length and the index of its last element.
        if (dp[i] > maxLen) {
            maxLen = dp[i];
            maxIdx = i;
        }
    }

    // 4. Reconstruct the path of the largest divisible subset.
    const result: number[] = [];
    let currentIdx = maxIdx;
    while (currentIdx !== -1) {
        result.push(nums[currentIdx]);
        currentIdx = prev[currentIdx];
    }
    
    // The result is constructed in reverse order. The problem doesn't mandate a specific order,
    // but examples suggest sorted order. Reversing provides a sorted (ascending) subset.
    return result.reverse();
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.