We're given an array and need to split every element into exactly k groups where each group has the same sum. Every element must belong to exactly one group, and no group can be empty.
If the total sum of the array isn't divisible by k, the answer is immediately false. If it is divisible, each subset must sum to totalSum / k. So the problem reduces to: can we partition all elements into k subsets, each summing to a fixed target?
This is a partitioning problem, which belongs to the NP-complete family, so there is no known polynomial-time algorithm for it. The constraint nums.length <= 16 is what makes it tractable here. With at most 16 elements, exponential approaches like backtracking or bitmask DP run fast enough. The work is in choosing one of those approaches and pruning it well enough to pass within time limits.
Key Constraints:
1 <= nums.length <= 16 - With n up to 16, there are 2^16 = 65,536 possible subsets. That bound is small enough for bitmask DP and for backtracking with pruning.1 <= k <= nums.length - When k equals n, every element must be its own subset, which forces all elements to be equal.1 <= nums[i] <= 10^4 - The total sum stays at most 16 * 10^4 = 160,000, which fits comfortably in a 32-bit integer, so there is no overflow concern.
Intuition
Model the problem as k buckets, each needing to hold a sum of target = totalSum / k. We place numbers into buckets one at a time. If a number fits in a bucket (adding it does not exceed target), we place it and move to the next number. If no bucket can hold the current number, we backtrack and undo the previous placement.
A plain version of this explores k^n placements, too many even for n = 16. Pruning is what makes it practical. Four pruning rules cut the search space sharply:
- Sort the array in descending order. Larger numbers are harder to place, so trying them first reaches a dead end sooner and prunes more of the tree.
- If any single number exceeds the target, return false immediately.
- Stop after the first empty bucket. When the current number does not fit any bucket so far and the next bucket is empty (sum 0), every remaining empty bucket is interchangeable. Placing the number in one empty bucket produces the same state as placing it in any other, so trying the rest only repeats failed work. The code expresses this with
if (buckets[i] == 0) break;. - The same
break also handles the case where the number was placed in an empty bucket but the recursion failed. Backing out and trying a different empty bucket would explore an identical subtree, so the loop stops there too.
Algorithm
- Compute the total sum. If it's not divisible by k, return false.
- Set target = totalSum / k. If any element exceeds target, return false.
- Sort the array in descending order.
- Create an array of k buckets, each starting at 0.
- For each number (starting from the largest), try placing it in each bucket:
- If the bucket's current sum plus the number doesn't exceed target, place it and recurse.
- If the bucket's sum equals 0 (empty bucket) and we failed, don't try other empty buckets.
- Backtrack if no valid placement exists.
- If all numbers are placed successfully, return true.
Example Walkthrough
1Initial: sorted descending, target=5, 4 buckets all empty 4 empty buckets, each needs to reach target sum = 5
2Step 1: Place 5 in Bucket 1 (0+5=5). Bucket 1 full! Bucket 1: +5 = 5 (full!)
3Step 2: Place 4 in Bucket 2 (0+4=4). Step 3: Place 3 in Bucket 3 (0+3=3) Bucket 2: +4 = 4. Bucket 3: +3 = 3
4Step 4: Place 3 in Bucket 4 (0+3=3). Buckets: [5, 4, 3, 3] Bucket 4: +3 = 3
5Step 5: Place 2 in Bucket 3 (3+2=5). Bucket 3 full! Bucket 3: +2 = 5 (full!)
6Step 6: Place 2 in Bucket 4 (3+2=5). Bucket 4 full! Bucket 4: +2 = 5 (full!)
7Step 7: Place 1 in Bucket 2 (4+1=5). All buckets = 5. Return true! Bucket 2: +1 = 5 (full!). All buckets = target!
Code
- Time Complexity: O(k^n) in the worst case, where n is the length of nums. Each of the n numbers can potentially be placed in any of the k buckets. Pruning strategies (sorting descending, skipping empty buckets) reduce the practical runtime significantly.
- Space Complexity: O(n + k) for the recursion stack (depth n) and the buckets array (size k).
Backtracking is fast in practice, but its worst case is O(k^n) and the actual runtime depends on how well the pruning rules fit a given input. The next approach uses bitmask dynamic programming, which trades extra memory for a fixed O(n * 2^n) bound that does not depend on pruning.
Intuition
Instead of filling buckets one number at a time, we represent which numbers have been used so far as a bitmask. With n <= 16 numbers, a 16-bit integer encodes any subset of numbers.
The state is the bitmask of used numbers, and for each state we store whether it can be reached such that every completed subset along the way summed to exactly target. The running sum of used elements, taken modulo target, tells us how full the current bucket is. When that sum crosses a multiple of target, one bucket is complete and the next one starts, so there is no need to track a bucket index separately.
The guard bucketFill + nums[j] <= target is what enforces the invariant. Let s = subsetSum[mask]. Since every reachable state was built by additions that never pushed the current bucket past target, the completed buckets each total exactly target, and s % target is precisely the fill level of the in-progress bucket. An addition that keeps bucketFill + nums[j] <= target either stays within the current bucket or exactly completes it (s % target returns to 0), so the invariant holds for the new state by induction. When the full mask is reached, s equals the total sum, every bucket closed at exactly target, and a valid partition exists.
Algorithm
- Compute total sum. If not divisible by k, return false.
- Set target = totalSum / k. If any element exceeds target, return false.
- Create a boolean DP array of size 2^n, initialized to false. Set dp[0] = true (empty set is valid).
- For each bitmask state from 0 to 2^n - 1:
- If dp[state] is false, skip it.
- Compute the current sum of all used elements, then take currentSum % target to find how much of the current bucket is filled.
- For each unused number j, if adding nums[j] doesn't exceed the current bucket's remaining capacity, set dp[state | (1 << j)] = true.
- Return dp[(1 << n) - 1] (whether using all numbers is achievable).
Example Walkthrough
1Initial: target=5, mask=000 (no elements used), bucket fill=0 Base case: empty set (mask=000) is reachable, sum=0
2mask=000: try adding each element. dp[001], dp[010], dp[100] all reachable From 000: reach 001 (sum=2), 010 (sum=3), 100 (sum=5)
3mask=001 (sum=2, fill=2): add 3 → fill=5, bucket done! dp[011]=true From 001: add 3 → 011 (sum=5, fill=0, bucket done!)
4mask=011 (sum=5, fill=0): bucket {2,3} done! Add 5 to new bucket → dp[111]=true From 100: add 2 → 101, add 3 → 110
5mask=100 (sum=5, fill=0): bucket {5} done, but adding 2 or 3 leads to a dead end later From 011: add 5 → 111 (sum=10, fill=0, both buckets done!)
6dp[111]=true! Partition: {2,3} and {5}, both sum to 5 dp[111]=true → all elements used, all buckets filled. Return true!
Code
- Time Complexity: O(n 2^n), where n is the length of nums. We iterate through all 2^n bitmask states, and for each state, we try adding each of the n elements. With n <= 16, this is at most 16 65,536 = about 1 million operations.
- Space Complexity: O(2^n) for the dp and subsetSum arrays. With n = 16, that's 2 * 65,536 entries, which is very manageable.