Partition Equal Subset Sum
MEDIUMDescription
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
Example 1:
Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5] Output: false Explanation: The array cannot be partitioned into equal sum subsets.
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= 100
Approaches
Checkout 3 different approaches to solve Partition Equal Subset Sum. Click on different approaches to view the approach and algorithm in detail.
Brute-Force Recursion
This approach explores all possible subsets of the given array nums using recursion. For each element, we make two choices: either include it in the current subset or not. We continue this process until we find a subset that sums up to the target value (half of the total sum) or exhaust all possibilities.
Algorithm
- Calculate the total sum of all elements in the
numsarray. - If the total sum is odd, it's impossible to partition it into two equal halves, so return
false. - If the total sum is even, calculate the
targetsum, which istotal_sum / 2. - Define a recursive helper function, say
canPartitionRecursive(index, target), that returnstrueif a subset summing totargetcan be formed using elements fromnums[index]onwards. - Base Cases for the recursion:
- If
targetis 0, it means we have found a valid subset, so returntrue. - If
targetbecomes negative orindexgoes beyond the array bounds, it's an invalid path, so returnfalse.
- If
- Recursive Step: For the element at
nums[index], explore two choices:- Include
nums[index]: Make a recursive callcanPartitionRecursive(index + 1, target - nums[index]). - Exclude
nums[index]: Make a recursive callcanPartitionRecursive(index + 1, target).
- Include
- The result for the current state is
trueif either of the two choices returnstrue. - The initial call to start the process is
canPartitionRecursive(0, target).
First, we check a fundamental condition: if the total sum of all numbers in the array is odd, it's impossible to divide them into two subsets of equal sum. In this case, we can immediately return false. If the sum is even, we set our target to half of the total sum. The problem is now transformed into a search for a subset that adds up to this target.
We implement this search using a recursive function. This function explores every possible combination by making two recursive calls at each step for each number: one call that includes the current number in the subset (subtracting its value from the target) and another that excludes it (leaving the target unchanged). If any of these recursive paths eventually reduces the target to zero, it means we've found a valid partition, and we return true. If all paths are explored without finding such a subset, we return false.
class Solution {
public boolean canPartition(int[] nums) {
int totalSum = 0;
for (int num : nums) {
totalSum += num;
}
if (totalSum % 2 != 0) {
return false;
}
int targetSum = totalSum / 2;
return canPartitionRecursive(nums, 0, targetSum);
}
private boolean canPartitionRecursive(int[] nums, int index, int target) {
// Base case: If target is 0, we found a subset.
if (target == 0) {
return true;
}
// Base case: If we run out of numbers or target becomes negative.
if (index >= nums.length || target < 0) {
return false;
}
// Recursive step:
// 1. Include the number at the current index.
boolean include = canPartitionRecursive(nums, index + 1, target - nums[index]);
// 2. Exclude the number at the current index.
boolean exclude = canPartitionRecursive(nums, index + 1, target);
return include || exclude;
}
}
Complexity Analysis
Pros and Cons
- Simple to conceptualize and implement.
- Follows a clear, divide-and-conquer logic.
- Extremely inefficient due to its exponential time complexity.
- Leads to a 'Time Limit Exceeded' error on most platforms for non-trivial inputs because it re-computes the same subproblems multiple times.
Code Solutions
Checking out 4 solutions in different languages for Partition Equal Subset Sum. Click on different languages to view the code.
Video Solution
Watch the video walkthrough for Partition Equal Subset Sum
Similar Questions
5 related questions you might find useful
Patterns:
Data Structures:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.