DSA Factory
Free Backtracking lessonsBacktracking · Stage 4 · Mastery · Step 4

Share the numbers equally

Decide whether numbers can be split into k groups with the same sum, by filling the groups one number at a time and pruning groups that would be tried twice or overflow. About 26 minutes.

A target per group

If numbers can be split into k groups with equal sums, each group must sum to the total divided by k. If that division is not exact, or the biggest number exceeds that target, the answer is no at once.

Otherwise, keep a running sum for each of the k groups, and place the numbers one by one, trying each group. A placement is only allowed if the group's sum does not go above the target.

Target: total divided by k, which must be exact.
Place a number: in a group that stays within the target.
In code
share = sum(items) // people
leftover = sum(items) % people
Split 4, 3, 2, 3, 5, 2, 1 into 4 groups of equal sum. The total is 20, so each group sums to 5.
5
0
4
1
3
2
3
3
2
4
2
5
1
6
i

5 fills the first group on its own (sum 5).

Move 1 of 4

Prune the repeats

Sort the numbers from big to small and place the big ones first, as they fail fastest. Two groups with the same current sum are interchangeable, so for one number try only one of them. Remember the sums already tried for this number in a small set.

If all the numbers are placed, every group is full, since the total matches the sum of the targets. The search then returns yes. If every choice for some number fails, undo and return no.

Big numbers first: they fail fastest.
Equal group sums: try just one of them.
In code
if sums[g] in seen:
    continue    # a group tried already
Quick check

Why try only one of several groups that have the same current sum?

  1. AThey are interchangeable, so the outcome is the same whichever is chosen
  2. BThe first one is always the best
  3. CThe rules require it
Show the answer

They are interchangeable, so the outcome is the same whichever is chosen. Trying more than one only repeats work.

Your problem

Partition to k equal sum subsets

You get a list nums of positive whole numbers and a number k. Return true if the numbers can be split into k non-empty groups, every number going to exactly one group, so that all the groups have the same sum. Otherwise return false.

Example
nums = [4, 3, 2, 3, 5, 2, 1], k = 4 → true

1 ≤ k ≤ length of nums ≤ 16 · 1 ≤ nums[i] ≤ 10,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve