Partition to K Equal Sum Subsets (LeetCode 698): Solution and Explanation

Medium
Array
Dynamic Programming
Backtracking
Bit Manipulation
Memoization
Bitmask

Given an array nums and an integer k, decide whether the numbers can be split into k non-empty groups that all have the same sum. Every number must be used exactly once.

Intuition

The sum of every group is forced. If the groups are equal and they use every number, each must sum to total / k. So the first check is cheap: if total % k is not zero, the answer is false, and if any single number is larger than the target, it can never fit anywhere.

After that, picture k buckets that each hold exactly target. Take the numbers one at a time and drop each into some bucket that still has room. If all numbers get placed without any bucket overflowing, every bucket is at most target and the buckets add up to total = k * target, so every bucket is exactly full.

When a number fits nowhere, the last decision was wrong. Backtracking takes the previous number back out of its bucket and tries the next bucket for it. This explores every assignment in principle, so two prunings keep it fast.

First, place the big numbers first. A large number has only a few buckets it can go into, so bad partial assignments get caught near the top of the search tree rather than after many small numbers were placed. Second, empty buckets are interchangeable. If putting a number into an empty bucket led to failure, putting it into another empty bucket is the same situation with the labels swapped, so the loop stops there.

Approach: Backtracking over k buckets

  1. Compute total. If total % k != 0, return false. Otherwise target = total / k.
  2. Sort nums in descending order. If nums[0] > target, return false.
  3. Keep an array buckets of k running sums, all zero.
  4. Define place(i): if i == len(nums), every number is placed, so return true.
  5. For each bucket b, if buckets[b] + nums[i] <= target, add the number, recurse on i + 1, and return true if that succeeds. Otherwise subtract the number again.
  6. If buckets[b] is zero after the attempt, break: the remaining buckets are empty too and would give the same result.
  7. If no bucket worked, return false so the caller undoes its choice. The answer is place(0).

Step-by-step example

nums = [4,3,2,3,5,2,1], k = 4
  1. total = 20, which divides by 4, so target = 5.
  2. Sorted descending: [5,4,3,3,2,2,1]. The largest value 5 does not exceed the target.
  3. 5 goes into bucket 0, filling it to 5.
  4. 4 does not fit bucket 0 (5 + 4 = 9), so it goes into bucket 1, which now holds 4.
  5. 3 skips buckets 0 and 1 (both would overflow) and lands in bucket 2. The next 3 lands in bucket 3.
  6. 2 skips buckets 0 and 1 and fills bucket 2 to 5. The next 2 fills bucket 3 to 5.
  7. 1 skips the full bucket 0 and lands in bucket 1, filling it to 5. Every number is placed, so the function returns true with no backtracking needed.

Code: Python, Java, C++

1class Solution:
2    def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
3        total = sum(nums)
4        if total % k != 0:
5            return False
6        target = total // k
7        nums.sort(reverse=True)
8        if nums[0] > target:
9            return False
10        buckets = [0] * k
11
12        def place(i: int) -> bool:
13            if i == len(nums):
14                return True
15            for b in range(k):
16                if buckets[b] + nums[i] <= target:
17                    buckets[b] += nums[i]
18                    if place(i + 1):
19                        return True
20                    buckets[b] -= nums[i]
21                if buckets[b] == 0:
22                    break
23            return False
24
25        return place(0)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(k^n)

In the worst case each of the n numbers can try each of the k buckets. Sorting descending and the empty-bucket break cut this down enormously in practice, and n is at most 16.

Space

O(n + k)

The recursion is at most n levels deep and the bucket sums take k integers.

Other approaches

Bitmask DP (time O(n * 2^n), space O(2^n))

Let dp[mask] be the fill level of the current bucket after using the numbers in mask, taken modulo target. A mask is reachable if some number can be added to a smaller reachable mask without exceeding the target. The answer is whether the full mask is reachable. It has a predictable running time that does not depend on luck in the search.

Fill one bucket at a time (time O(k * 2^n), space O(2^n))

Build bucket 1 fully from unused numbers, then bucket 2, and so on, using a used bitmask and memoizing failed masks. It is the same search seen from the other side and pairs naturally with memoization.

Common mistakes

  • Skipping the divisibility check, which leads to a target that is not an integer and a pointless search.
  • Forgetting to undo the placement after a failed recursion, which leaves stale sums in the buckets.
  • Leaving out the empty-bucket break. The answer stays correct but the search repeats the same failing work k times at every level and can time out.
  • Sorting ascending instead of descending. Small numbers fit everywhere, so the search branches widely before it finds out a large number has no home.

Frequently asked questions

Why is it enough that no bucket overflows?

If all numbers are placed and each bucket is at most target, the buckets together hold total = k * target. A bucket below target would force another one above it, which is impossible, so every bucket is exactly target.

Why does the loop break on an empty bucket?

All empty buckets look the same to the rest of the search. If placing the number in the first empty bucket failed, placing it in any other empty bucket is the identical situation and would fail as well.

How is this related to Partition Equal Subset Sum?

That problem is the special case k = 2. With two groups you only need one subset that sums to half the total, which a knapsack DP handles. For general k you have to track several buckets at once, which is why backtracking or bitmask DP is used.

Does the frequency limit in the constraints matter?

It limits how many identical values exist, which keeps the number of equivalent branches small. The algorithm itself does not depend on it.