Split the numbers into two equal-sum halves. Track which sums up to half the total are reachable, adding one number at a time, right to left.
▼The problem
LeetCode 416 (Medium). Given an array nums of positive integers, return true if it can be split into two subsets whose sums are equal.
Examples: [1, 5, 11, 5] → true (11 against 1 + 5 + 5); [1, 2, 3, 5] → false (the total, 11, is odd).
The solution
def canPartition(nums):
total = sum(nums)
if total % 2:
return False
target = total // 2
reachable = [False] * (target + 1)
reachable[0] = True
for num in nums:
for s in range(target, num - 1, -1):
reachable[s] |= reachable[s - num]
return reachable[target]Transcript
Partition Equal Subset Sum. Given an array of positive numbers, can you split it into two groups with equal sums? Every number goes on one side of the scale, and the sides must balance.
Take one, five, eleven and five: twenty-two in all, so each side needs eleven. Eleven alone on one pan balances one, five and five on the other: true. Now one, two, three and five. They total eleven, which is odd, so no split is even: false.
The simple way tries every subset. Each number is in or out, so four numbers give sixteen subsets, and two of them make eleven. But n numbers give two to the n. Thirty numbers already means over a billion.
Here's the trick. If one side makes half the total, the other side gets the rest. So we only need one subset that sums to eleven: the target. Keep a row of lamps, one for each sum from zero to eleven. Lamp zero starts lit: taking nothing sums to zero. For each number, lamp s lights if lamp s minus that number is already lit.
Let's light them. The one lights lamp one. The five lights six, from one, and five, from zero. Eleven jumps from zero straight to lamp eleven: the target! The last five adds ten. Lamp eleven is lit, so the answer is true.
In code, an odd total returns false. Otherwise, the target is half, and reachable starts with just zero. For each number, sweep the sums from the target down to that number: s is reachable if s minus num was. Why down? Going up, the one would light lamp one, then lamp two from lamp one, then three: one number used again and again. Going down, each number counts once.
Each number sweeps at most target plus one lamps, so the time is order n times target. One row of lamps is all the memory: order target space.
Odd total? False. Otherwise, light sums up to half, sweeping down. That's Partition Equal Subset Sum.