sagelearnai

Partition to K Equal Sum Subsets

Difficulty: Medium · Pattern: Backtracking · LeetCode #698

Return true if nums can be split into k non-empty subsets with equal sums.

Examples

text
nums = [4,3,2,3,5,2,1], k = 4  →  true    ((5),(1,4),(2,3),(2,3))
nums = [1,2,3,4], k = 3        →  false

Hints

  1. Quick rejections: sum % k != 0, or the largest number is greater than sum / k.
  2. Fill one bucket at a time to exactly target, then start the next one. The state is just which numbers are used (a bitmask), because the current bucket's fill is usedSum % target.

Approach

target = sum / k. Sort in descending order, so big numbers fail fast.

Bitmask DP / memoized DFS: can(mask) asks whether the numbers not in mask can complete the partition. The current bucket's fill is sum(mask) % target. Try every unused i with fill + nums[i] ≤ target. When the fill reaches target it wraps to 0, which starts the next bucket. Memoize on mask: there are 2ⁿ states with n ≤ 16, so O(n · 2ⁿ) total.

Without memoization, the bucket-by-bucket search also needs the "skip identical empty buckets" pruning to stay fast.

Complexity

Time: O(n · 2ⁿ). Space: O(2ⁿ).

Python solution
from functools import lru_cache

def canPartitionKSubsets(nums, k):
    total = sum(nums)
    if total % k:
        return False
    target = total // k
    nums = sorted(nums, reverse=True)
    if nums[0] > target:
        return False
    n = len(nums)
    @lru_cache(maxsize=None)
    def can(mask, fill):
        if mask == (1 << n) - 1:
            return True
        for i in range(n):
            if not mask >> i & 1 and fill + nums[i] <= target:
                if can(mask | 1 << i, (fill + nums[i]) % target):
                    return True
        return False
    return can(0, 0)
JavaScript solution
function canPartitionKSubsets(nums, k) {
  const total = nums.reduce((a, b) => a + b, 0);
  if (total % k) return false;
  const target = total / k, a = [...nums].sort((x, y) => y - x), n = a.length;
  if (a[0] > target) return false;
  const memo = new Map();
  const can = (mask, fill) => {
    if (mask === (1 << n) - 1) return true;
    if (memo.has(mask)) return memo.get(mask);
    let ok = false;
    for (let i = 0; i < n && !ok; i++) {
      if ((mask >> i) & 1 || fill + a[i] > target) continue;
      ok = can(mask | (1 << i), (fill + a[i]) % target);
    }
    memo.set(mask, ok);
    return ok;
  };
  return can(0, 0);
}