Partition Equal Subset Sum – Solution & Complexity
Solution Walkthrough
Step 1: Reduce to subset sum
- Splitting into two equal halves means finding a subset that sums to exactly
total / 2. - If
totalis odd, no such subset exists, so returnfalseimmediately. - Otherwise the question becomes: can any subset reach
target = total / 2?
- Splitting into two equal halves means finding a subset that sums to exactly
Step 2: Fill a 2D reachability table
- Let
dp[i][s]betruewhen some subset of the firstivalues sums tos. - A sum of
0is always reachable with the empty subset. - Each value is either skipped (
dp[i-1][s]) or taken (dp[i-1][s - nums[i-1]]).
- Let
Step 3: Compress to one boolean row
- Each row only reads the row directly above, so a single boolean array of size
target + 1suffices. - Iterate the inner
sumfrom high down tovalue; going downward guarantees each number is used at most once (a 0/1 knapsack, not unbounded).
- Each row only reads the row directly above, so a single boolean array of size
Step 4: Optimal 1D solution
- Start with
dp[0] = true. - For every value, mark
dp[sum]reachable wheneverdp[sum - value]was already reachable, scanning sums downward. - The answer is
dp[target].
- Start with
Step 5: Dry run
Trace
nums = [1,5,11,5],target = 11.- Start: reachable sums
{0}. - After
1:{0,1}. - After
5:{0,1,5,6}. - After
11:{0,1,5,6,11,...}—11is now reachable, so the answer istrue.
- Start: reachable sums
Step 6: Common mistakes and follow-ups
- Iterating the inner sum upward, which reuses the same element multiple times and turns it into unbounded knapsack.
- Forgetting the odd-total shortcut, or comparing against
totalinstead oftotal / 2. - Allocating
dpof sizetargetinstead oftarget + 1and missing the exact-target cell. - Follow-up: how would you recover the actual subset, not just whether one exists?
Step 7: Edge cases to test mentally
- A single element can never be split, so the answer is
false. - An odd total is always
false. - Two equal elements are always
true.
- A single element can never be split, so the answer is
Step 8: Final full solution and complexity
Target half the total and fill a 1D subset-sum table, scanning sums downward per value. Time is
O(n * sum)and extra space isO(sum).