Partition Equal Subset Sum
The key insight: 'split into two equal-sum subsets' reduces to a single reachability question — can some subset of the numbers add up to exactly half the total? dp[j] tracks whether sum j is reachable using the numbers processed so far; sweeping j from target down to num for every number (instead of up) ensures each number is only ever used once per subset, so it can't double-count the same item. If dp[target] ends up true, a valid equal split exists.
Details
Animated on: nums=[1,5,11,5], total sum=22, target=11, can array be partitioned?
Problem:Partition Equal Subset SumMedium
Dynamic Programming
step 1 / 8
Start: dp[0]=true, dp[1..11]=false, target=11 (half of total sum 22)
1FUNCTION canPartition(nums):2 total = the sum of all numbers in nums3 IF total is odd: RETURN false4 target = total / 25 dp = a list of target+1 falses (dp[j] = is sum j reachable)6 dp[0] = true (a sum of 0 is always reachable)7 FOR each num in nums:8 FOR j from target down to num:9 dp[j] = dp[j] or dp[j-num]10 RETURN dp[target]
← / → step · space play · Home restart
Every step in words
Show all 8 steps
- Start: dp[0]=true, dp[1..11]=false, target=11 (half of total sum 22)
- Process num=1, j=1 (right to left): dp[1] = dp[1] || dp[0] = false || true = true, first item makes sum 1 possible
- Process num=5, j=6: dp[6] = dp[6] || dp[1] = false || true = true (1+5=6); j=5: dp[5] = dp[5] || dp[0] = false || true = true (5=5)
- Process num=11, j=11: dp[11] = dp[11] || dp[0] = false || true = true, single element 11 reaches target sum
- Process second num=5, j=11: dp[11] = dp[11] || dp[6] = true || true = true (5+5+1=11, using both 5s and 1)
- Verify: subset {{11}} sums to 11, subset {{1,5,5}} also sums to 11, array can be partitioned into two equal-sum subsets
- Side effect: dp[10]=true (5+5=10) also achievable but target was dp[11]; partition still valid
- Answer: dp[11]=true, array CAN be partitioned into two equal-sum subsets: {{11}} and {{1,5,5}}
Now solve it yourself
Watching is the first half. The second is writing it without the animation.