Partition Equal Subset Sum

Decide whether an array of positive numbers can be split into two groups with the same sum.

Given an array nums of positive integers, return true if it can be split into two subsets with equal sums, and false otherwise. The two subsets are two groups of numbers that between them hold every number of the array exactly once.

Example 1
Input: nums = [1, 5, 11, 5]
Output: true
Explanation: [1, 5, 5] and [11] both add up to 11.
Example 2
Input: nums = [1, 2, 3, 5]
Output: false
Explanation: the total is 11, which is odd, so no two groups can have equal sums.
Solution

The Idea

Picture two friends sharing four coins worth 1, 5, 11 and 5, and each wants the same amount. The coins are worth 22 together, so each friend must end up with 11. One takes the 11 coin, the other takes 1, 5 and 5, and the split is fair.

That points at a simpler question. If one group of numbers adds up to exactly half the total, the numbers left over add up to the other half on their own: 22 - 11 = 11. So the whole problem is: can some of the numbers make exactly half the total? In the code that half is called target. Example 2 never gets that far, because a total of 11 has no whole-number half.

How do we find such a group? Each number is either in it or out, so four numbers allow 2 × 2 × 2 × 2 = 16 different picks. But many picks share a sum. Picking 1 and the first 5 makes 6, and so does picking 1 and the second 5. What matters is which sums can be made at all, and in Example 1 only the sums from 0 to 11 are of interest.

So take the numbers one at a time and keep track of every sum from 0 to 11 that some pick of the numbers so far can make. Such a sum is called reachable. At the start only 0 is reachable, by picking nothing. When a new number arrives, each reachable sum can stay as it is, or grow by that number. Look at the picture below.

A table with one row per step and one column per sum from 0 to 11. Row start: 0. After 1: 0 and 1. After 5: 0, 1, 5 and 6, with +5 arrows from 0 and 1. After 11: 0, 1, 5, 6 and 11, with 11 outlined. After 5 again: 0, 1, 5, 6, 10 and 11.

Each row shows which sums are reachable, with a teal "yes" in the sum's column. In the row labelled "start", only 0 says yes. The row "after 1" adds 1. In the row "after 5", the blue arrows marked +5 show 0 and 1 growing into 5 and 6. The row "after 11" makes 11 reachable from 0 + 11, outlined in orange: half of 22 can be made, so the answer to Example 1 is true. The last row, "after 5 again", adds 10, from 5 + 5.

Each row is worked out only from the row above it, and no sum is worked out twice. Answering the big question by filling a table of smaller answers, here "which sums can the first few numbers make?", is called dynamic programming.

Solution Approach

Trying every pick of numbers works, but the number of picks doubles with each new number. The code instead settles three things: a quick check on the total, how to store the table of reachable sums, and the order in which a new number updates it.

Trying every pick

Why not simply try every pick? For each number the search has two choices, in or out, so the picks double with every number. Four numbers give 16 picks, but 30 numbers give 1,073,741,824. The table of reachable sums never grows past one row per number, each with target + 1 entries.

Checking the total first

What if the total is odd? Two groups of whole numbers with equal sums always have an even total, so an odd total means false before any table is built. That is what happens to Example 2, with its total of 11.

Storing the table in one row

Each row in the picture is built only from the row above it, so the code keeps a single row and updates it in place. It is a boolean array named reachable, with one entry for each sum from 0 to target. reachable[s] is true when some pick of the numbers seen so far adds up to s.

At the start, reachable[0] is true and every other entry is false. When a number v arrives, a sum s becomes reachable if s - v already was, because adding v to that pick makes s. Sums above target are left out: all numbers are positive, so a pick that already passes half the total can only grow.

Updating from the top sum down

In which order should s go? Updating one row in place hides a catch. Say the number 1 arrives and s goes upward. At s = 1, reachable[1] turns true from reachable[0]. At s = 2, the code reads reachable[1], just set by this same 1, so 2 turns true too, as if the 1 were used twice.

Going from target down to v avoids that. The entry reachable[s - v] belongs to a smaller sum, which this number has not touched yet, so it still describes picks without v. Each number is then used at most once.

Java Solution

The method canPartition works in these steps:

  1. First, add up all the numbers into total with a loop. If total is odd, return false.
  2. Set target to total / 2 and create the boolean array reachable with target + 1 entries, one for each sum from 0 to target. Set reachable[0] to true, since picking nothing makes 0.
  3. Take the numbers one by one with an outer loop, calling the current number v. Inside, a second loop moves s from target down to v, and sets reachable[s] to true whenever reachable[s - v] is true.
  4. After the last number, return reachable[target]: whether half the total can be made.

The extra parameter showRows makes the method print the reachable sums after each number, through the helper printRow, so the rows of the picture can be checked. The main method runs Example 1 with the rows shown, then Example 2, [1, 2, 5], [3, 3, 3, 4, 5], [7, 7] and the single number [4].

Java
public class PartitionEqualSubset {

    public static boolean canPartition(int[] nums, boolean showRows) {
        int total = 0;
        for (int v : nums) {
            total += v;
        }
        if (total % 2 != 0) {
            return false;                      // an odd total has no two equal halves
        }
        int target = total / 2;
        boolean[] reachable = new boolean[target + 1];   // reachable[s]: some pick sums to s
        reachable[0] = true;                   // picking nothing gives 0
        if (showRows) {
            printRow("start", reachable);
        }
        for (int v : nums) {
            for (int s = target; s >= v; s--) {          // downward: v is used at most once
                if (reachable[s - v]) {
                    reachable[s] = true;
                }
            }
            if (showRows) {
                printRow("after " + v, reachable);
            }
        }
        return reachable[target];
    }

    static void printRow(String label, boolean[] reachable) {
        StringBuilder sb = new StringBuilder(String.format("%-9s", label));
        for (int s = 0; s < reachable.length; s++) {
            if (reachable[s]) {
                sb.append(' ').append(s);
            }
        }
        System.out.println(sb);
    }

    public static void main(String[] args) {
        System.out.println(canPartition(new int[] {1, 5, 11, 5}, true));
        System.out.println(canPartition(new int[] {1, 2, 3, 5}, false));
        System.out.println(canPartition(new int[] {1, 2, 5}, false));
        System.out.println(canPartition(new int[] {3, 3, 3, 4, 5}, false));
        System.out.println(canPartition(new int[] {7, 7}, false));
        System.out.println(canPartition(new int[] {4}, false));
    }
}

Running it prints:

Output
start     0
after 1   0 1
after 5   0 1 5 6
after 11  0 1 5 6 11
after 5   0 1 5 6 10 11
true
false
false
true
true
false

The rows from start to the second after 5 match the picture: 11 first shows up in the row after 11, and 10 joins in the last row. The true under them is the answer to Example 1, and the false after it is Example 2, stopped by its odd total of 11.

Next comes [1, 2, 5], with an even total of 8 and so a target of 4. Without the 5, its picks make only 1, 2 and 3, and any pick with the 5 is already past 4, so it prints false. [3, 3, 3, 4, 5] prints true, because 4 + 5 and 3 + 3 + 3 both make 9, and [7, 7] splits into 7 and 7. The single 4 prints false: its target is 2, smaller than 4, so the inner loop never runs and reachable[2] stays false.

The false for [1, 2, 5] also depends on the downward loop. A version whose inner loop runs upward, from v to target, prints true for that array: the 1 alone makes 1, 2, 3 and 4 in one pass, as if it could be used four times.

The original implementation, PartitionEqualSubsetSum.java, is on GitHub.

Complexity

The work is one pass to add up the numbers, then one downward sweep over reachable for each number.

  • Time: O(n × target), because each of the n numbers in nums sweeps at most target entries of reachable, and adding up the total takes only n more steps.
  • Space: O(target), because the whole table is one boolean array of target + 1 entries, reused for every number instead of keeping one row per number.

Counting the ways to reach a sum, instead of checking whether one exists, leads to Target Sum.