← Whiteboard questions

Partition Equal Subset Sum

Split boxes into two groups of equal weight

DSA, Medium, 1-D DP

Which structure or algorithm, and what does it cost.

A list weights holds the weights of boxes. Decide whether the boxes can be shared between two trucks so that both trucks carry exactly the same total weight. Every box goes on exactly one truck. Return true if it can be done and false if not.

Examples

Input weights = [4, 9, 5, 2, 6]
Output true
Why the total is 26. One truck takes 4 and 9, the other takes 5, 2 and 6, and both carry 13.
Input weights = [3, 3, 3, 5]
Output false
Why the total 14 is even, but no boxes add up to 7.
Input weights = [10]
Output false
Why edge case: one box leaves the other truck empty, so the totals differ.

Constraints

Your answer must contain

Target Aim for O(n x S) time and O(S) memory, where S is half the total weight.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

If both trucks carry the same weight, each carries exactly half the total. When can that fail straight away?

Hint 2 the approach

The job becomes finding some boxes that add up to exactly half. Think about which totals the first few boxes can make, one box at a time.

Hint 3 the key step

Keep a table of which totals up to half can be made. For each box, mark old total plus its weight. Loop downwards so a box is used once.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every way to split the boxes: each box goes on one of two trucks, so there are 2^n splits, and each is added up. For 40 boxes that is over 10^12 splits. It cannot handle 120 boxes.

Better method

Memoised recursion. Let ok(i, rest) say whether boxes from position i on can make the total rest. A box is either left out or used, and rest shrinks by its weight. Save each answer. There are at most n x S states, so this is O(n x S) time and O(n x S) memory.

Best method

If the total is odd, the answer is false at once. Otherwise each truck must carry exactly half of the total, called half. So the task is to find some boxes that add up to half. Keep a table where entry s says whether some of the boxes seen so far add up to exactly s. Only entry 0 is true at the start. For each box of weight w, every entry s that is at least w becomes true if entry s - w was true before this box. Loop s from high to low, so a box is not used twice. The answer is the entry for half, because the boxes that make half go on one truck and the rest make the other half.

Hand trace

Run on [4, 9, 5, 2, 6]. The total is 26, so half is 13. Before any box, only the total 0 can be made. After 4: {0, 4}. After 9: {0, 4, 9, 13}, and 13 is already there as 4 + 9. After 5 (totals above 13 are not kept): {0, 4, 5, 9, 13}. After 2: {0, 2, 4, 5, 6, 7, 9, 11, 13}. After 6: {0, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}. Total 13 can be made, so the answer is true.

Code

def can_balance(weights):
    total = sum(weights)
    if total % 2:
        return False
    half = total // 2
    reach = [True] + [False] * half     # reach[s]: some of the boxes seen so far add up to exactly s
    for w in weights:
        for s in range(half, w - 1, -1):    # downwards, so each box is used at most once
            if reach[s - w]:
                reach[s] = True
    return reach[half]

Time and memory

O(n x S) time, where S is half the total weight: each box updates the table once, and S is at most 3,600 here, so about 432,000 steps for 120 boxes. O(S) memory for the table.

Common mistakes

  • Skipping the odd-total check. For [1, 2, 4] the total is 7, half becomes 3 by whole-number division, and 1 + 2 wrongly gives true.
  • Looping up through the totals instead of down. One box can then be added again and again, so [2, 6] wrongly gives true.
  • Using plain recursion over every split with no saved answers. It makes over 10^12 calls for 40 boxes.

Related problems

More 1-D DP problems
Partition Equal Subset Sum: walkthrough and Python solution