Partition Equal Subset Sum
Medium
Topics
Given an array nums of positive integers, return true if it can be split into two subsets with equal sum.
Example 1
one half, summing to 11
The total is 22, so each half must reach 11 — and the shaded cells do. This is subset-sum: a boolean row indexed by target, swept right to left per value so that each value is used at most once.
Cells are the array values; the small numbers underneath are indices.
Input: nums = [1,5,11,5] Output: true
Example 2
The total is 11, which is odd — so it cannot split into two equal halves and the answer is
false before any searching. Checking the parity of the sum first is the cheap early exit.Input: nums = [1,2,3,5] Output: false
Constraints
- 1 <= nums.length <= 200
- 1 <= nums[i] <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
Two subsets with equal sums means each holds exactly half the total, so an odd total is an immediate no. What remains is: can some subset reach total / 2? That is subset-sum, and the classic 0/1 knapsack over a boolean reachability array answers it.
dp[j] means "some subset of the items considered so far sums to j". Each item is offered once. The problem is NP-hard in the item values, but the constraints bound the total, which is exactly what makes the pseudo-polynomial table affordable.
Approach
- Return false if the total is odd; otherwise set
t = total / 2. - Start with
dp[0] = trueand everything else false. - For each item
x, walkjfromtdown toxand setdp[j]ifdp[j - x]holds. - Return
dp[t].
Dry Run
nums = [1,5,11,5] total = 22 is even, so t = 11
after item reachable sums
(none) [0]
1 [0, 1]
5 [0, 1, 5, 6]
11 [0, 1, 5, 6, 11]
5 [0, 1, 5, 6, 10, 11]
dp[11] = true -> {11} and {1,5,5} both sum to 11Complexity
- Time — O(n · sum): with
n <= 200and values at most 100, the total is at most 20,000 andtat most 10,000, so roughly 2×10⁶ updates. - Space — O(sum): one boolean row of length
t + 1. The two-dimensional table is the natural first formulation and reduces to this row because each item reads only the previous state.
Common Pitfalls
- Walking the inner loop upward. That lets a single item be consumed more than once — it turns 0/1 knapsack into unbounded knapsack. On
[1,2,5]the ascending version reports true by using the 1 four times; the correct answer is false. - Dropping the odd-total check. Integer division then truncates the half and the table answers a different question without complaining.
- Calling the problem NP-hard and stopping. It is — in the magnitude of the values — but the bounded total is precisely the condition under which the DP is the expected answer.
- Returning
dp[t]from a table sized tototalrather thant, which doubles the work for no gain. - Missing the bitset form.
bits |= bits << xwith the answer read off bittis the same algorithm with a word-sized constant-factor win, and it is a good thing to offer once the O(n · sum) version is on the board.
Full Solution — all languages
class Solution:
def canPartition(self, nums):
total = sum(nums)
if total % 2:
return False
t = total // 2
dp = [False] * (t + 1)
dp[0] = True
for x in nums:
for j in range(t, x - 1, -1):
if dp[j - x]:
dp[j] = True
return dp[t]import java.util.*;
class Solution {
public boolean canPartition(int[] nums) {
int total = 0;
for (int x : nums) total += x;
if (total % 2 == 1) return false;
int t = total / 2;
boolean[] dp = new boolean[t + 1];
dp[0] = true;
for (int x : nums) for (int j = t; j >= x; j--) if (dp[j - x]) dp[j] = true;
return dp[t];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool canPartition(vector<int>& nums) {
int total = 0;
for (int x : nums) total += x;
if (total % 2 == 1) return false;
int t = total / 2;
vector<bool> dp(t + 1, false);
dp[0] = true;
for (int x : nums) for (int j = t; j >= x; j--) if (dp[j - x]) dp[j] = true;
return dp[t];
}
};/**
* @param {number[]} nums
* @return {boolean}
*/ var canPartition = function(nums) {
let total = 0;
for (const x of nums) total += x;
if (total % 2 === 1) return false;
const t = total / 2;
const dp = new Array(t + 1).fill(false);
dp[0] = true;
for (const x of nums) for (let j = t; j >= x; j--) if (dp[j - x]) dp[j] = true;
return dp[t];
};