Partition to K Equal Sum Subsets explained
To decide whether a list of positive integers can be split into k groups with equal sums, first check that the total divides by k and that no single value exceeds total / k. Then fill one group at a time by backtracking, largest values first, with two prunes: skip a value equal to one that just failed in the same spot, and give up as soon as the first value placed into an empty group fails. For small lists, a bitmask DP over which values are used runs in O(n × 2^n) and needs no pruning tricks.
By Evin JohnPublished 9 min read
The problem, in plain terms
You get a list of positive integers and a number k. Every value must go into exactly one of k groups, and all groups must end with the same sum. Return true if that is possible and false otherwise. You only report yes or no, though the backtracking version can be extended to return the groups.
7 2 5 4 3 6 1, k = 4
total 28, target 7
groups: [7] [5 2] [4 3] [6 1] -> true
5 5 4 2 2, k = 3
total 18, target 6
each 5 needs a 1 to reach 6; there is none -> false
3 3 2 2 2 2, k = 2
total 14, target 7
groups: [3 2 2] [3 2 2] -> trueClarify early: are all values positive, how large can the list be, and is k at least 1. The size question decides the approach. The bitmask DP needs memory for 2^n states, which is fine for about twenty values and hopeless for a hundred.
Rejections that cost nothing
Two checks remove many inputs before any search. If the total is not a multiple of k, no equal split exists. If the largest value is bigger than target = total / k, that value cannot fit in any group. When k is 1 the answer is always true. These are worth writing first because they also make the search code simpler: inside it, every value is known to fit in an empty group.
Why greedy fails
The tempting shortcut fills one group at a time, taking the largest remaining value that still fits. On 3 3 2 2 2 2 with k = 2 and target 7, it puts both 3s into the first group (6), then no 2 fits, and it reports false. The real answer is true: each group takes one 3 and two 2s. Committing to a locally good choice can block the global solution, so the search has to be able to undo choices.
Approach 1: fill buckets one at a time
Sort the values from largest to smallest so that hard-to-place items are tried first and failures show up early. Then build the first group by choosing values in increasing index order until it reaches the target, mark them used, and start the next group from the beginning of the list. When k - 1 groups are complete, the unused values must add up to the target automatically, so you can stop there.
Two prunes keep this fast in practice. First, if a value fails at some point in a group, an equal value at the same point fails the same way, so skip it. Second, if the group is empty and the first value you place into it leads to failure, return false at once. That value is the largest unused one, it has to go into some group, and all the remaining empty groups are interchangeable, so no other arrangement can help.
def can_partition_k(nums, k):
total = sum(nums)
if total % k:
return False
target = total // k
nums = sorted(nums, reverse=True) # big items first fail fast
if nums[0] > target:
return False
used = [False] * len(nums)
def fill(start, done, current):
if done == k - 1:
return True # the leftovers must add up to target
if current == target:
return fill(0, done + 1, 0) # bucket full, start the next one
tried = None
for i in range(start, len(nums)):
if used[i] or nums[i] == tried or current + nums[i] > target:
continue
used[i] = True
if fill(i + 1, done, current + nums[i]):
return True
used[i] = False
tried = nums[i] # an equal value here would fail the same way
if current == 0:
return False # the largest unused item fits no bucket
return False
return fill(0, 0, 0)Filling buckets one at a time, instead of placing each item into one of k buckets, matters for two reasons. It avoids exploring the same split with the buckets relabeled, and it makes the set of used items a complete description of the search state, which is what the DP below relies on.
Approach 2: bitmask DP over used items
Represent the used items as a bitmask. Because groups are filled in order, a mask fully determines how far the current group is filled: it is the sum of the used values modulo target. So store, for each reachable mask, that partial fill, and from each reachable mask try adding one more unused item as long as it does not overflow the current group. When a group reaches the target exactly, the fill wraps to 0 and the next group begins. The answer is true if the mask with every item used is reachable with a fill of 0.
// fill[mask] = how full the current bucket is after placing the items in mask,
// or -1 if that set of items can't be placed in full buckets plus one partial one.
function canPartitionK(nums, k) {
const total = nums.reduce((a, b) => a + b, 0);
if (total % k !== 0) return false;
const target = total / k;
const n = nums.length;
const fill = new Array(1 << n).fill(-1);
fill[0] = 0;
for (let mask = 0; mask < 1 << n; mask++) {
if (fill[mask] === -1) continue;
for (let i = 0; i < n; i++) {
const next = mask | (1 << i);
if (next === mask || fill[next] !== -1) continue;
if (fill[mask] + nums[i] <= target) {
fill[next] = (fill[mask] + nums[i]) % target; // a full bucket wraps to 0
}
}
}
return fill[(1 << n) - 1] === 0;
}Storing a single number per mask is enough because every way of reaching a mask has used the same items, so it has the same total and the same partial fill. The overflow check never lets a group pass the target, so a fill of 0 on the full mask means every group closed exactly. In JavaScript, 1 << n stays a correct positive number only while n is at most 30, which is far beyond what the 2^n array could hold anyway.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Try every assignment of items to groups | O(k^n) | O(n) recursion |
| Bucket-by-bucket backtracking with prunes | Exponential in the worst case; prunes cut it heavily in practice | O(n) recursion and used flags |
| Same, with a memo keyed on the used mask | O(n × 2^n) | O(2^n) |
| Bitmask DP | O(n × 2^n) | O(2^n) |
Deciding this is NP-hard in general (with k = 2 it is the classic partition problem), so no known method is polynomial in n for arbitrary values. When values are small and k = 2, a subset-sum table indexed by sum is the better tool. Mention that when the interviewer asks about scaling.
Edge cases to test
- k = 1: always true.
- k equal to the list length: true only if every value is the same.
- A value larger than total / k: false without searching.
- A total that does not divide by k: false.
- Many equal values, such as eight 3s with k = 4, to make sure the duplicate prune does not wrongly reject a valid split.
Common mistakes
- Using a greedy fill, as shown above.
- Memoizing on the used mask while placing items into any of k buckets. The mask alone no longer describes the state, so the memo can return wrong answers. The memo is safe only with bucket-by-bucket filling.
- Applying the overflow and empty-group prunes when zeros or negative values are allowed. Both assume every value is positive.
- Forgetting to undo used[i] after a failed branch.
- Carrying on from the current index after a bucket closes instead of restarting at 0, which leaves earlier unused items out of every later bucket.
How to explain it out loud
Fictional example
- Candidate
- First the free checks: the total has to divide by k, and the biggest value can't exceed the target. Otherwise it's false.
- Candidate
- Greedy won't work. With 3 3 2 2 2 2 and two groups it puts both 3s together and gets stuck. So I'll backtrack, one group at a time, biggest values first.
- Candidate
- Two prunes: an equal value that failed in the same place fails again, and if the first item in an empty group fails, nothing will work, since all empty groups look the same. If n is small I can also do a DP over used masks in n times 2 to the n.
Related problems
Listing every group that reaches a single target, rather than asking for a full split, is Combination Sum II, and with digits only it is Combination Sum III. For a number split into parts to make the biggest product, see Integer Break. For heavier constraint pruning on a grid, read Sudoku Solver.
Natively when you rehearse search problems
Pruning arguments are where candidates lose points, so practice stating why each cut is safe. Natively, which runs on Mac and Windows, can read this kind of problem from a screenshot during practice and lay out an approach with code, so you can compare its search with yours prune by prune. The transcript afterward shows whether you gave the free checks first. More on AI interview help.
Questions people ask
How do you solve Partition to K Equal Sum Subsets?
Reject if the total does not divide by k or a value exceeds total / k. Then sort descending and fill one group at a time by backtracking, skipping equal values that already failed and stopping when the first item in an empty group fails. For small n, a bitmask DP also works.
Why does a greedy approach fail for k equal sum subsets?
Filling each group with the largest values that fit can block the solution. With 3, 3, 2, 2, 2, 2 and k = 2, greedy puts both 3s together and gets stuck, but 3 + 2 + 2 twice works.
What is the time complexity of the bitmask DP?
O(n × 2^n) time and O(2^n) space, since each of the 2^n masks of used items is processed once and tries n items.
Is Partition to K Equal Sum Subsets NP-hard?
The general problem is NP-hard; with k = 2 it is the classic partition problem. That is why the solutions are exponential in n and rely on pruning or a small n.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
