Partition Equal Subset Sum
Pattern: Subsequences and knapsack
Two subsets with equal sums each hold half the total. So the question is subset sum with target total / 2; an odd total is impossible.
The problem
Return whether the array can be split into two subsets with equal sums. [1, 5, 11, 5] is true; [1, 2, 3, 5] is false.
Think first
- What must each half add up to?
- When is it impossible at once?
- Which earlier problem is left?
Hints
Brute force, and why it fails
Try every split: 2ⁿ.
The key insight
If one subset reaches total / 2, the remaining items automatically make the other half.
Dry run
| half | 11 |
|---|
nums [1, 5, 11, 5]: total 22, half 11.
Step 1 of 2
The plan
if total odd: false
return subsetSum(nums, total / 2)
Complexity
- Time
O(n × total)- Space
O(total)
Subset sum with target total / 2.
Edge cases
- One item: false.
- Odd total: false.
- All equal values, even count: true.
I've built my logic, show the code
Java
class Solution {
public boolean canPartition(int[] nums) {
int total = 0;
for (int x : nums) total += x;
if (total % 2 == 1) return false; // an odd total cannot split evenly
int half = total / 2;
boolean[] can = new boolean[half + 1]; // subset sum: can some subset reach half?
can[0] = true;
for (int x : nums) for (int s = half; s >= x; s--) if (can[s - x]) can[s] = true;
return can[half];
}
}C++
class Solution {
public:
bool canPartition(vector<int>& nums) {
int total = 0;
for (int x : nums) total += x;
if (total % 2 == 1) return false; // an odd total cannot split evenly
int half = total / 2;
vector<bool> can(half + 1, false); // subset sum: can some subset reach half?
can[0] = true;
for (int x : nums) for (int s = half; s >= x; s--) if (can[s - x]) can[s] = true;
return can[half];
}
};Python
class Solution:
def canPartition(self, nums: list[int]) -> bool:
total = sum(nums)
if total % 2:
return False # an odd total cannot split evenly
reach = {0} # every subset sum seen so far
for x in nums:
reach |= {s + x for s in reach if s + x <= total // 2}
return total // 2 in reachCommon mistakes
- Forgetting the odd check.
- Requiring both subsets to be non-empty when the problem does not.