Partition Equal Subset Sum
Decide whether an array of positive numbers can be split into two groups with the same sum.
Given an array numstruefalse
Example 1
Output: true
Explanation: [1, 5, 5] and [11] both add up to 11.
Example 2
Output: false
Explanation: the total is 11, which is odd, so no two groups can have equal sums.
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
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.
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
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
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
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 booleanreachabletargetreachable[s]trues
At the start, reachable[0]truefalsevss - vvstarget
Updating from the top sum down
In which order should sssreachable[1]reachable[0]sreachable[1]
Going from targetvreachable[s - v]v
Java Solution
The method canPartition
- First, add up all the numbers into
with a loop. Iftotal is odd, returntotal .false - Set
totarget and create thetotal / 2 arrayboolean withreachable entries, one for each sum from 0 totarget + 1 . Settarget toreachable[0] , since picking nothing makes 0.true - Take the numbers one by one with an outer loop, calling the current number
. Inside, a second loop movesv froms down totarget , and setsv toreachable[s] whenevertrue isreachable[s - v] .true - After the last number, return
: whether half the total can be made.reachable[target]
The extra parameter showRowsprintRowmain[1, 2, 5][3, 3, 3, 4, 5][7, 7][4]
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:
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 startafter 5after 11truefalse
Next comes [1, 2, 5]targetfalse[3, 3, 3, 4, 5]true[7, 7]falsetargetreachable[2]false
The false[1, 2, 5]vtargettrue
The original implementation,
Complexity
The work is one pass to add up the numbers, then one downward sweep over reachable
- Time: O(n × target), because each of the n numbers in
sweeps at mostnums entries oftarget , and adding up the total takes only n more steps.reachable - Space: O(target), because the whole table is one
array ofboolean entries, reused for every number instead of keeping one row per number.target + 1
Counting the ways to reach a sum, instead of checking whether one exists, leads to