KatInterview

698. Partition to K Equal Sum Subsets

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

Method: Backtracking with Optimization

This problem asks if we can partition an array nums into k non-empty subsets with equal sums. This is a classic combinatorial search problem, which can be solved using backtracking. Given the small constraint on the number of elements (N <= 16), an algorithm with exponential time complexity is feasible.

Solution

Partition to K Equal Sum Subsets in Python

class Solution:
    def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
        total_sum = sum(nums)
        if total_sum % k != 0:
            return False
        
        target = total_sum // k
        
        # Sort descending to place larger elements first, enabling faster pruning.
        nums.sort(reverse=True)

        if nums[0] > target:
            return False

        subset_sums = [0] * k

        def backtrack(index: int) -> bool:
            # Base case: All numbers have been placed.
            if index == len(nums):
                return True
            
            current_num = nums[index]
            # Try to place the current number in one of the k subsets.
            for i in range(k):
                if subset_sums[i] + current_num <= target:
                    subset_sums[i] += current_num
                    # Recurse for the next number.
                    if backtrack(index + 1):
                        return True
                    # Backtrack.
                    subset_sums[i] -= current_num
                    
                    # Optimization: If we tried putting `current_num` in an empty
                    # subset and it failed, no need to try other empty subsets.
                    if subset_sums[i] == 0:
                        break
            
            return False

        return backtrack(0)

Partition to K Equal Sum Subsets in Java

class Solution {
    public boolean canPartitionKSubsets(int[] nums, int k) {
        int totalSum = 0;
        for (int num : nums) {
            totalSum += num;
        }

        if (k <= 0 || totalSum % k != 0) {
            return false;
        }
        
        int target = totalSum / k;

        // Sort to process larger elements first (by iterating backwards).
        Arrays.sort(nums);

        if (nums[nums.length - 1] > target) {
            return false;
        }

        int[] subsetSums = new int[k];
        // Start backtracking from the largest element.
        return backtrack(nums, nums.length - 1, subsetSums, target);
    }

    private boolean backtrack(int[] nums, int index, int[] subsetSums, int target) {
        // Base case: If we have placed all numbers, we are done.
        if (index < 0) {
            return true;
        }

        int currentNum = nums[index];
        // Try to place the current number in one of the k subsets.
        for (int i = 0; i < subsetSums.length; i++) {
            if (subsetSums[i] + currentNum <= target) {
                subsetSums[i] += currentNum;
                // Recurse for the next number (the next smaller one).
                if (backtrack(nums, index - 1, subsetSums, target)) {
                    return true;
                }
                // Backtrack.
                subsetSums[i] -= currentNum;

                // Optimization: If subsetSums[i] is 0, it means we tried to place
                // currentNum in an empty subset and failed. Since all empty subsets
                // are symmetrical, there's no need to try other empty subsets.
                if (subsetSums[i] == 0) {
                    break;
                }
            }
        }

        return false;
    }
}

Partition to K Equal Sum Subsets in C++

class Solution {
public:
    bool canPartitionKSubsets(vector<int>& nums, int k) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }

        if (k <= 0 || sum % k != 0) {
            return false;
        }
        
        int target = sum / k;
        // Sort in descending order to prune the search space faster.
        // Larger elements are placed first, which quickly reduces the target sum.
        sort(nums.rbegin(), nums.rend());

        if (nums[0] > target) {
            return false;
        }

        vector<int> subsetSums(k, 0);
        return backtrack(nums, 0, subsetSums, target);
    }

private:
    bool backtrack(const vector<int>& nums, int index, vector<int>& subsetSums, int target) {
        // Base case: If we have placed all numbers, we are done.
        if (index == nums.size()) {
            return true;
        }

        int currentNum = nums[index];
        // Try to place the current number in one of the k subsets.
        for (int i = 0; i < subsetSums.size(); ++i) {
            if (subsetSums[i] + currentNum <= target) {
                subsetSums[i] += currentNum;
                // Recurse for the next number.
                if (backtrack(nums, index + 1, subsetSums, target)) {
                    return true;
                }
                // Backtrack.
                subsetSums[i] -= currentNum;

                // Optimization: If subsetSums[i] is 0, it means we tried to place
                // currentNum in an empty subset and failed. Since all empty subsets
                // are symmetrical, there's no need to try other empty subsets.
                if (subsetSums[i] == 0) {
                    break;
                }
            }
        }

        return false;
    }
};

Partition to K Equal Sum Subsets in TypeScript

function canPartitionKSubsets(nums: number[], k: number): boolean {
    const totalSum = nums.reduce((sum, num) => sum + num, 0);

    if (k <= 0 || totalSum % k !== 0) {
        return false;
    }

    const target = totalSum / k;

    // Sort in descending order to place larger elements first for pruning.
    nums.sort((a, b) => b - a);

    if (nums[0] > target) {
        return false;
    }

    const subsetSums = new Array(k).fill(0);

    function backtrack(index: number): boolean {
        // Base case: All numbers have been placed.
        if (index === nums.length) {
            return true;
        }

        const currentNum = nums[index];
        // Try to place the current number in one of the k subsets.
        for (let i = 0; i < k; i++) {
            if (subsetSums[i] + currentNum <= target) {
                subsetSums[i] += currentNum;
                // Recurse for the next number.
                if (backtrack(index + 1)) {
                    return true;
                }
                // Backtrack.
                subsetSums[i] -= currentNum;

                // Optimization: If we tried placing currentNum in an empty subset and it failed,
                // there's no need to try other empty subsets due to symmetry.
                if (subsetSums[i] === 0) {
                    break;
                }
            }
        }

        return false;
    }

    return backtrack(0);
};

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.