Problem 58 · Dynamic Programming
Partition Equal Subset Sum
01Problem
Given an array of positive integers, return whether it can be split into two subsets with equal sums.
02Key insight
Reduces to 0/1 subset-sum targeting total/2. A Python int used as a bitset (reach |= reach << x) does the whole DP row in one word-parallel shift.
03Solution
Try it first.
TimeO(n * sum / w) with w-bit words
SpaceO(sum)
tests.py · 4 passing
tests.pypython4 lines
assert can_partition([1,5,11,5]) is True
assert can_partition([1,2,3,5]) is False
assert can_partition([2,2]) is True
assert can_partition([1]) is False04Staff-level follow-up
Sum is huge but n is small (~40)? Switch to meet-in-the-middle: enumerate subset sums of each half (2^20) and match with sort + two pointers.