Partition to K Equal Sum Subsets (LeetCode 698): Solution and Explanation
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
- Compute
total. Iftotal % k != 0, return false. Otherwisetarget = total / k. - Sort
numsin descending order. Ifnums[0] > target, return false. - Keep an array
bucketsofkrunning sums, all zero. - Define
place(i): ifi == len(nums), every number is placed, so return true. - For each bucket
b, ifbuckets[b] + nums[i] <= target, add the number, recurse oni + 1, and return true if that succeeds. Otherwise subtract the number again. - If
buckets[b]is zero after the attempt, break: the remaining buckets are empty too and would give the same result. - 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
- total = 20, which divides by 4, so target = 5.
- Sorted descending: [5,4,3,3,2,2,1]. The largest value 5 does not exceed the target.
- 5 goes into bucket 0, filling it to 5.
- 4 does not fit bucket 0 (5 + 4 = 9), so it goes into bucket 1, which now holds 4.
- 3 skips buckets 0 and 1 (both would overflow) and lands in bucket 2. The next 3 lands in bucket 3.
- 2 skips buckets 0 and 1 and fills bucket 2 to 5. The next 2 fills bucket 3 to 5.
- 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)1class Solution {
2 public boolean canPartitionKSubsets(int[] nums, int k) {
3 int total = 0;
4 for (int x : nums) total += x;
5 if (total % k != 0) return false;
6 int target = total / k;
7 Arrays.sort(nums);
8 if (nums[nums.length - 1] > target) return false;
9 int[] buckets = new int[k];
10 return place(nums, nums.length - 1, buckets, target);
11 }
12
13 private boolean place(int[] nums, int i, int[] buckets, int target) {
14 if (i < 0) return true;
15 for (int b = 0; b < buckets.length; b++) {
16 if (buckets[b] + nums[i] <= target) {
17 buckets[b] += nums[i];
18 if (place(nums, i - 1, buckets, target)) return true;
19 buckets[b] -= nums[i];
20 }
21 if (buckets[b] == 0) break;
22 }
23 return false;
24 }
25}1class Solution {
2public:
3 bool canPartitionKSubsets(vector<int>& nums, int k) {
4 int total = accumulate(nums.begin(), nums.end(), 0);
5 if (total % k != 0) return false;
6 int target = total / k;
7 sort(nums.rbegin(), nums.rend());
8 if (nums[0] > target) return false;
9 vector<int> buckets(k, 0);
10 return place(nums, 0, buckets, target);
11 }
12
13private:
14 bool place(vector<int>& nums, int i, vector<int>& buckets, int target) {
15 if (i == (int)nums.size()) return true;
16 for (int b = 0; b < (int)buckets.size(); b++) {
17 if (buckets[b] + nums[i] <= target) {
18 buckets[b] += nums[i];
19 if (place(nums, i + 1, buckets, target)) return true;
20 buckets[b] -= nums[i];
21 }
22 if (buckets[b] == 0) break;
23 }
24 return false;
25 }
26};Time and space complexity
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.
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.