Algorithm Day90 - Partition Equal Subset Sum
π§© Problem Description
Given a non-empty array nums containing only positive integers, determine if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Return true if such a partition exists, otherwise return false.
π¬ Examples
Example 1
1 | Input: nums = [1,5,11,5] |
Example 2
1 | Input: nums = [1,2,3,5] |
π‘ Intuition
If the total sum is odd, itβs impossible to split into two equal subsets. Otherwise, the problem reduces to: can we find a subset with sum equal to target = totalSum / 2?
This is the classic subset sum problem and can be solved using dynamic programming (0/1 knapsack style) or using a bitset optimization. We aim for a boolean DP where dp[s] indicates whether a subset with sum s is achievable.
π’ Java Code (1D DP - optimized 0/1 knapsack)
1 | class Solution { |
Alternative: Bitset (very fast in practice)
1 | import java.util.*; |
Note: Javaβs
BitSetdoesnβt provide a directshiftLeftmethod β you can implement shifting by iterating or using along-based trick for fixed-size bitsets. The 1D boolean DP is simpler and sufficiently fast for typical constraints.
β± Complexity Analysis
- Time: O(n Γ target) β where
nis the number of elements. - Space: O(target) β 1D DP array.
βοΈ Summary
- Check total sum parity first.
- Reduce to subset-sum with target = totalSum / 2.
- Use 1D DP (iterate backwards) to avoid reusing elements.
- Early exit if
dp[target]becomestrueduring iteration.
Related problems: lc-494 (Target Sum), lc-216 (Combination Sum III), lc-698 (Partition to K Equal Sum Subsets).