Algo-Sim › Advanced DP

Partition to K Equal Sum Subsets

Medium · Advanced DP · step through it in Java, Python and C++ on your own input

Can the items split into k groups of equal sum? Bitmask DP over the set of used items, tracking how full the open bucket is.

Problem

Given an integer array nums and an integer k, return true if it is possible to divide the array into k non-empty subsets whose sums are all equal.

Constraints

Edge cases to test

Follow-up questions

Why is one number per mask enough?
Items fill buckets one at a time, so the fill of the open bucket is (sum of the mask) mod target: O(2ⁿ · n).
What prunes the backtracking version?
Sort descending, skip equal items that failed in the same bucket, and stop when an empty bucket fails.

Solution

Java

public boolean canPartitionKSubsets(int[] nums, int k) {
    int n = nums.length, total = Arrays.stream(nums).sum();
    if (total % k != 0) return false;
    int target = total / k;
    Arrays.sort(nums);
    // dp[mask] = fill of the open bucket, -1 = unreachable
    int[] dp = new int[1 << n];
    Arrays.fill(dp, -1);
    dp[0] = 0;
    for (int mask = 0; mask < (1 << n); mask++) {
        if (dp[mask] < 0) continue;
        for (int i = 0; i < n; i++) {
            if ((mask >> i & 1) == 1) continue;
            if (dp[mask] + nums[i] > target) break;
            int next = mask | 1 << i;
            if (dp[next] < 0) dp[next] = (dp[mask] + nums[i]) % target;
        }
    }
    return dp[(1 << n) - 1] == 0;
}

Python

def can_partition_k_subsets(nums, k):
    n, total = len(nums), sum(nums)
    if total % k:
        return False
    target = total // k
    nums = sorted(nums)
    # dp[mask] = fill of the open bucket, -1 = unreachable
    dp = [-1] * (1 << n)
    dp[0] = 0
    for mask in range(1 << n):
        if dp[mask] < 0:
            continue
        for i in range(n):
            if mask >> i & 1:
                continue
            if dp[mask] + nums[i] > target:
                break
            nxt = mask | 1 << i
            if dp[nxt] < 0:
                dp[nxt] = (dp[mask] + nums[i]) % target
    return dp[(1 << n) - 1] == 0

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool canPartitionKSubsets(vector<int> &nums, int k) {
        int n = int(nums.size()), total = accumulate(nums.begin(), nums.end(), 0);
        if (total % k != 0) return false;
        int target = total / k;
        sort(nums.begin(), nums.end());
        // dp[mask] = fill of the open bucket, -1 = unreachable
        vector<int> dp(1 << n, -1);
        dp[0] = 0;
        for (int mask = 0; mask < (1 << n); mask++) {
            if (dp[mask] < 0) continue;
            for (int i = 0; i < n; i++) {
                if (mask >> i & 1) continue;
                if (dp[mask] + nums[i] > target) break;
                int next = mask | 1 << i;
                if (dp[next] < 0) dp[next] = (dp[mask] + nums[i]) % target;
            }
        }
        return dp[(1 << n) - 1] == 0;
    }
};

More Advanced DP problems