Partition Equal Subset Sum
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #416
Given positive integers nums, return true if they can be split into two groups with equal sums.
Examples
text
nums = [1, 5, 11, 5] → true ([1, 5, 5] and [11])
nums = [1, 2, 3, 5] → false (total 11 is odd)
nums = [2, 2, 3, 5] → falseHints
- If the total is odd, it's impossible. Otherwise, can some subset sum to total / 2?
- That's a 0/1 knapsack: each number is used at most once.
- With a 1-D table, iterate the target sum downwards so a number isn't reused.
Approach
Let target = total / 2 (return false if total is odd). dp[t] = whether some subset of the numbers processed so far sums to t; dp[0] = True. For each number x, update t from target down to x: dp[t] |= dp[t − x]. Going downward ensures dp[t − x] still reflects subsets without x (0/1, not unbounded). The answer is dp[target].
Python bonus: a bitset bits |= bits << x does the same thing very fast.
Complexity
Time: O(n × sum/2). Space: O(sum/2).
Python solution
def canPartition(nums):
total = sum(nums)
if total % 2:
return False
target = total // 2
dp = [True] + [False] * target
for x in nums:
for t in range(target, x - 1, -1):
if dp[t - x]:
dp[t] = True
return dp[target]JavaScript solution
function canPartition(nums) {
const total = nums.reduce((a, b) => a + b, 0);
if (total % 2) return false;
const target = total / 2, dp = new Array(target + 1).fill(false); dp[0] = true;
for (const x of nums) for (let t = target; t >= x; t--) if (dp[t - x]) dp[t] = true;
return dp[target];
}