Partition Equal Subset Sum
Medium
Dynamic ProgrammingKnapsack
Problem
Given a non-empty array of positive integers, decide if you can split it into two subsets with equal sum.
Example 1
Input: [1,5,11,5]
Output: true
Explain: [1,5,5] and [11]
Example 2
Input: [1,2,3,5]
Output: false
Constraints
- 1 ≤ length ≤ 200
- 1 ≤ nums[i] ≤ 100
Approach — Dynamic Programming
This is a Dynamic Programming problem. The idea: break the problem into overlapping subproblems and build the answer up, caching results so nothing is recomputed. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) to O(n²) time.
Solution code
Python
class Solution:
def canPartition(self, nums):
total = sum(nums)
if total % 2:
return False
target = total // 2
seen = {0}
for x in nums:
seen |= {s + x for s in seen if s + x <= target}
return target in seen
Java
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
for (int n : nums) sum += n;
if ((sum & 1) == 1) return false;
int target = sum / 2;
boolean[] dp = new boolean[target + 1];
dp[0] = true;
for (int n : nums)
for (int j = target; j >= n; j--)
dp[j] = dp[j] || dp[j - n];
return dp[target];
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Partition Equal Subset Sum interactively → ← All solutions