Partition of a set intoK subsets with equal sum

Pattern: Subsets

hard

Each subset must sum to total / k. Place the values one by one, largest first, into k buckets without overflowing any. If a value fails in an empty bucket, it fails in every empty bucket, so stop trying.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given an array of positive whole numbers and k, return whether it can be split into k non-empty groups with equal sums. For example, [4, 3, 2, 3, 5, 2, 1] with k = 4 gives true (5, 1 4, 2 3, 2 3), and [1, 2, 3, 4] with k = 3 gives false.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet (LeetCode's Partition to K Equal Sum Subsets is the same task). The function name canPartitionKSubsets follows LeetCode.

Think first

  • What must each group sum to? When is the answer false at once?
  • If you place values one at a time, what choice is made for each?
  • Why try big values first?

Hints

    Brute force, and why it fails

    Try every assignment of values to buckets: kⁿ. A DP over bit masks of used values is O(2ⁿ × n). Bucket backtracking with the two prunes is usually far faster on typical inputs.

    The key insight

    Most of the search is symmetric: empty buckets are interchangeable. Breaking that symmetry, and failing big values early, cuts the tree down to a manageable size.

    Dry run

    target5

    nums = [4, 3, 2, 3, 5, 2, 1] and k = 4. The total is 20, so each bucket must reach 5. Sorted big first, 5 4 3 3 2 2 1.

    Step 1 of 4

    The plan

    if total mod k != 0: return false
    target = total / k; sort a from big to small; bucket = k zeros
    function fill(i):
        if i == n: return true
        for b in 0..k-1:
            if bucket[b] + a[i] > target: continue
            bucket[b] += a[i]
            if fill(i + 1): return true
            bucket[b] -= a[i]
            if bucket[b] == 0: stop
        return false
    return fill(0)
    

    Complexity

    Time
    O(kⁿ) worst
    Space
    O(n)

    The prunes make typical inputs fast, but the worst case is exponential. The recursion is n deep.

    Edge cases

    • k = 1: always true.
    • A value larger than the target: false.
    • k larger than the number of values: false, since groups must be non-empty.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public boolean canPartitionKSubsets(int[] nums, int k) {
            int total = 0;
            for (int v : nums) total += v;
            if (total % k != 0) return false;
            int[] a = nums.clone();
            Arrays.sort(a);                                 // try big values first: dead ends show up sooner
            for (int l = 0, r = a.length - 1; l < r; l++, r--) { int t = a[l]; a[l] = a[r]; a[r] = t; }
            return fill(a, 0, new int[k], total / k);
        }
    
        private boolean fill(int[] a, int i, int[] bucket, int target) {
            if (i == a.length) return true;                 // every value placed, and no bucket overflowed
            for (int b = 0; b < bucket.length; b++) {
                if (bucket[b] + a[i] > target) continue;
                bucket[b] += a[i];
                if (fill(a, i + 1, bucket, target)) return true;
                bucket[b] -= a[i];
                if (bucket[b] == 0) break;                  // an empty bucket failed, so every empty bucket would
            }
            return false;
        }
    }

    C++

    class Solution {
    public:
        bool canPartitionKSubsets(vector<int>& nums, int k) {
            int total = 0;
            for (int v : nums) total += v;
            if (total % k != 0) return false;
            vector<int> a = nums;
            sort(a.rbegin(), a.rend());                     // try big values first: dead ends show up sooner
            vector<int> bucket(k, 0);
            return fill(a, 0, bucket, total / k);
        }
    
        bool fill(vector<int>& a, size_t i, vector<int>& bucket, int target) {
            if (i == a.size()) return true;                 // every value placed, and no bucket overflowed
            for (size_t b = 0; b < bucket.size(); b++) {
                if (bucket[b] + a[i] > target) continue;
                bucket[b] += a[i];
                if (fill(a, i + 1, bucket, target)) return true;
                bucket[b] -= a[i];
                if (bucket[b] == 0) break;                  // an empty bucket failed, so every empty bucket would
            }
            return false;
        }
    };

    Python

    class Solution:
        def canPartitionKSubsets(self, nums: list[int], k: int) -> bool:
            total = sum(nums)
            if total % k:
                return False
            target = total // k
            a = sorted(nums, reverse=True)          # try big values first: dead ends show up sooner
            bucket = [0] * k
    
            def fill(i: int) -> bool:
                if i == len(a):
                    return True                     # every value placed, and no bucket overflowed
                for b in range(k):
                    if bucket[b] + a[i] > target:
                        continue
                    bucket[b] += a[i]
                    if fill(i + 1):
                        return True
                    bucket[b] -= a[i]
                    if bucket[b] == 0:
                        break                       # an empty bucket failed, so every empty bucket would
                return False
    
            return fill(0)

    Common mistakes

    • Forgetting the divisibility check.
    • Trying the same value in every empty bucket, which multiplies the work by k!.
    • Sorting small to big, which finds dead ends late.

    Similar problems