Partition to K Equal Sum Subsets

MediumBacktrackingLeetCode 698 ↗World 4-12
0:00 / 0:00

Split numbers into k groups with equal sums: find the target, place the biggest numbers first, and skip buckets that repeat a sum.

▼

The problem

Given an integer array nums and an integer k, return true if nums can be divided into k non-empty subsets whose sums are all equal.

Examples (both animated):

TRY IT ON LEETCODE ▶

The solution

def canPartitionKSubsets(nums, k):
    total = sum(nums)
    if total % k: return False
    target = total // k
    nums.sort(reverse=True)
    if nums[0] > target: return False
    bins = [0] * k
    def place(i):
        if i == len(nums): return True
        seen = set()
        for b in range(k):
            if bins[b] + nums[i] > target or bins[b] in seen:
                continue
            seen.add(bins[b])
            bins[b] += nums[i]
            if place(i + 1): return True
            bins[b] -= nums[i]
            if bins[b] == 0: break   # failed in an empty bin
        return False
    return place(0)

Transcript

Partition to K Equal Sum Subsets. Given a list of numbers and a count k, can you split the numbers into k groups with equal sums?

Take four, three, two, three, five, two, one, with k equal to four. The total is twenty, so each group must make five, and they can: five, four and one, three and two, three and two. True.

The naive way tries every number in every group: k to the n assignments. Seven numbers in four groups is over sixteen thousand.

Better: the target is the total over k. If it isn't whole, or the biggest number is larger, stop. Then sort big to small, and place each number in a group that stays within the target.

When a number fits nowhere, back up: take out the last number and try its next group. Take five, five, three, three, two, in two groups of nine. The fives split, the threes follow, and the two fits nowhere. Both threes come back out. Group two holds five, the same sum group one just failed with, so skip it. And a number that fails in an empty group fails in every empty group, so stop. False.

In code, each call places one number, and returns true once all are placed. It loops over the groups, skipping any that would pass the target or repeat a sum. It adds the number and recurses; on failure it takes it back, and breaks if the group is empty.

Now our example, target five. Five fills group one. Four starts group two. Three fits neither; groups three and four are both empty, so it opens just group three. The other three opens group four. The twos top up groups three and four, and one finishes group two. True, in eight calls.

The worst case is still exponential, but pruning cuts most branches. The space is order n for the recursion, plus k group sums.

Find the target, sort big first, back up and skip repeated sums. That's Partition to K Equal Sum Subsets.