Partition Equal Subset Sum (LeetCode 416): Solution and Explanation
Given an array of positive integers, decide whether you can split it into two groups whose sums are equal. Every number must go into exactly one of the two groups.
Watch it run step by step
Try your own input and write the code →Intuition
Start by simplifying what is being asked. If the two groups have equal sums, each must equal half of the total. So the question becomes whether some subset of the numbers adds up to exactly total / 2, and if the total is odd the answer is immediately no. Once you find one such subset, the leftover numbers automatically form the other half.
The brute force tries every subset, which is 2^n possibilities and hopeless for 200 numbers. But the values are small: each is at most 100, so the target is at most 10,000. That points to dynamic programming over sums rather than over subsets. This is the 0/1 knapsack pattern, where each item is either taken once or not at all.
Keep a boolean array dp where dp[j] means some subset of the numbers seen so far sums to j. Initially only dp[0] is true, thanks to the empty subset. When you process a new number num, any sum j becomes reachable if j - num was reachable before. The subtle part is the direction of the inner loop: iterating j from high to low ensures that dp[j - num] still reflects the state before num was added, so each number is used at most once.
Approach: 0/1 knapsack with a one-dimensional boolean DP
- Compute
total = sum(nums). If it is odd, return False. - Set
target = total // 2and createdpof lengthtarget + 1with onlydp[0] = True. - For each
num, loopjdownward fromtargettonum. - Set
dp[j] = dp[j] or dp[j - num], meaning sumjis reachable either without this number or by adding it to a reachablej - num. - After all numbers are processed, return
dp[target].
Step-by-step example
nums = [1,5,11,5]
- The total is 22, which is even, so
target = 11and only sum 0 is reachable. - Processing 1 makes sum 1 reachable. The reachable set is {0, 1}.
- Processing 5, going downward, marks 6 (from 1) and 5 (from 0). The reachable set is {0, 1, 5, 6}.
- Processing 11 marks 11 from 0, so
dp[11]is already True. The last 5 adds 10 (from 5) and keeps 11 reachable. dp[11]is True, so the function returns True. One valid split is [11] and [1, 5, 5].
Code: Python, Java, C++
1class Solution:
2 def canPartition(self, nums: List[int]) -> bool:
3 total = sum(nums)
4 if total % 2 != 0:
5 return False
6
7 target = total // 2
8 dp = [False] * (target + 1)
9 dp[0] = True
10
11 for num in nums:
12 for j in range(target, num - 1, -1):
13 dp[j] = dp[j] or dp[j - num]
14
15 return dp[target]1class Solution {
2 public boolean canPartition(int[] nums) {
3 int total = 0;
4 for (int num : nums) total += num;
5 if (total % 2 != 0) return false;
6
7 int target = total / 2;
8 boolean[] dp = new boolean[target + 1];
9 dp[0] = true;
10
11 for (int num : nums) {
12 for (int j = target; j >= num; j--) {
13 dp[j] = dp[j] || dp[j - num];
14 }
15 }
16
17 return dp[target];
18 }
19}1class Solution {
2public:
3 bool canPartition(vector<int>& nums) {
4 int total = 0;
5 for (int num : nums) total += num;
6 if (total % 2 != 0) return false;
7
8 int target = total / 2;
9 vector<bool> dp(target + 1, false);
10 dp[0] = true;
11
12 for (int num : nums) {
13 for (int j = target; j >= num; j--) {
14 dp[j] = dp[j] || dp[j - num];
15 }
16 }
17
18 return dp[target];
19 }
20};Time and space complexity
O(n × target)
For each of the n numbers, the inner loop runs over at most target + 1 sums, where target is half the total. With the given limits that is at most 200 × 10,000 cell updates.
O(target)
Only one boolean array of length target + 1 is kept, reused for every number.
Other approaches
Two-dimensional DP table (time O(n × target), space O(n × target))
Use dp[i][j] for whether the first i numbers can reach sum j. It is the same recurrence written out fully, which is easier to visualize but needs n times more memory.
Bitset of reachable sums (time O(n × target / w), space O(target / w))
Store reachable sums as bits of one big integer and update with bits |= bits << num, then test bit target. It performs the same knapsack with word-level parallelism and is very fast in practice.
Common mistakes
- Looping
jupward. Thendp[j - num]may already include the current number, which lets a number be reused and gives false positives such as [1, 3] appearing to reach 2. - Forgetting the odd-total check, which makes
total // 2round down and can report a split that does not exist. - Starting with
dp[0] = False. Sum zero must be reachable, or nothing else can ever become true. - Trying a greedy approach such as sorting and filling the larger half first. It fails on many inputs because the right subset is not built from the largest values.
Frequently asked questions
Why is Partition Equal Subset Sum a knapsack problem?
It reduces to asking whether a subset of the numbers sums to exactly half of the total. Choosing each number at most once to hit an exact sum is the 0/1 knapsack, or subset sum, problem.
Why does the inner loop go backwards?
Going from high sums to low sums means dp[j - num] has not yet been updated for the current number. That guarantees each number contributes at most once; looping forward would allow it to be used repeatedly.
What is the time complexity of Partition Equal Subset Sum?
It is O(n × target), where target is half the sum. This is pseudo-polynomial, so it is fast here because the values are small, but it would not scale if the numbers could be in the billions.
Can I solve it with recursion and memoization?
Yes. Recurse on (index, remaining sum), choosing to take or skip each number, and cache results. It has the same complexity, but the bottom-up array avoids recursion depth issues.