The user wants a program to solve the "Partition Equal Subset Sum" problem.
1. Understand the Problem:
Given a non-empty array of positive integers nums, determine if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
- Key Constraints/Properties:
- Total sum must be even. If it's odd, we can't split it into two equal integer halves.
- If the total sum is S, we need to find a subset of
nums that sums to S/2.
- This reduces the problem to the standard "Subset Sum Problem".
2. Algorithm Choice:
There are two main approaches:
- Recursion with Memoization (Top-Down): Good for understanding, but might hit recursion depth limits on large inputs.
- Dynamic Programming (Bottom-Up): Standard, efficient, and iterative.
- State:
dp[i][j] = boolean, is it possible to get sum j using the first i elements?
- Optimization: We only need the previous row to calculate the current row. We can use a 1D array.
- Space Complexity: O(target).
- Time Complexity: O(N⋅target).
3. Step-by-Step Solution (Dynamic Programming):
- Step 1: Calculate the total sum of the array.
- Step 2: Check if the sum is odd. If so, return
False.
- Step 3: Calculate target sum =
total_sum // 2.
- Step 4: Initialize a boolean array
dp of size target + 1.
dp[0] is always True (we can always make sum 0 with an empty subset).
- Initialize all others to
False.
- Step 5: Iterate through each number in
nums.
- Iterate backwards through the
dp array from target down to the current number's value.
- Update rule:
dp[j] = dp[j] or dp[j - num]
- Reason for backward iteration: We are using the values from the previous iteration (representing previous items). If we iterate forwards, we might use the same item multiple times for the current calculation (Unbounded Knapsack). Since this is the 0/1 Knapsack variant (use item or don't), we iterate backwards.
4. Code Structure:
I will provide a solution in Python because it's widely used and easy to read. I'll also include a C++ version for completeness, as it's often asked in competitive programming contexts.
5. Refinement and Edge Cases:
- Empty array? Problem says "non-empty", but handle gracefully or assume valid input.
- Single element? Return
False (unless it's 0, but problem says positive integers).
- Target > Sum? Impossible.
- Element > Target? Skip? Actually, the DP loop handles this naturally if the inner loop starts at
num.
6. Drafting the Python Code (Mental or Scratchpad):
class Solution:
def canPartition(self, nums: List[int]) -> bool:
total_sum = sum(nums)
if total_sum % 2 != 0:
return False
target = total_sum // 2
dp = [False] * (target + 1)
dp[0] = True
for num in nums:
# Iterate backwards
for j in range(target, num - 1, -1):
dp[j] = dp[j] or dp[j - num]
return dp[target]
7. Explanation:
I need to explain why this works.
- Concept: Reducing to Subset Sum.
- DP Array:
dp[i] represents whether a specific sum i is achievable.
- Looping: Explain the backward iteration logic (0/1 Knapsack).
8. Final Output Generation:
- Provide the problem definition.
- Provide the Python code.
- Explain the logic (Time/Space complexity).
- Provide a C++ alternative (good for robustness).
Let's double check the backward loop condition. range(target, num - 1, -1).
If num is 5 and target is 11.
j goes 11, 10, ..., 5.
If num > target, the range is empty, loop doesn't run. That's correct, we can't form a sum ≥num using num if num is already larger than the target, but technically we just don't update dp. The existing dp values remain. This is correct.
Let's write the response.
Here is a comprehensive solution to the Partition Equal Subset Sum problem.
The Problem
Given a non-empty array of positive integers nums, determine if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
The Logic
- Total Sum Check: If the sum of all numbers is odd, it is mathematically impossible to split them into two equal integer halves. We immediately return
False.
- Target Sum: If the total sum is even, we need to find a subset of numbers that adds up to
total_sum / 2. This transforms the problem into the classic Subset Sum Problem.
- Dynamic Programming: We use a boolean array
dp where dp[i] indicates whether a sum of i is achievable using the numbers processed so far.
Python Solution
This solution uses Space-Optimized Dynamic Programming (1D array) with O(N⋅S) time complexity and O(S) space complexity, where N is the length of nums and S is the target sum.
from typing import List
def canPartition(nums: List[int]) -> bool:
# Step 1: Calculate total sum
total_sum = sum(nums)
# Step 2: If sum is odd, it cannot be partitioned into two equal subsets
if total_sum % 2 != 0:
return False
# Step 3: The target we want to reach is half of the total sum
target = total_sum // 2
# Step 4: Initialize DP array
# dp[i] will be True if we can sum to 'i' using elements seen so far
dp = [False] * (target + 1)
dp[0] = True # Base case: sum of 0 is always achievable (empty subset)
# Step 5: Iterate through each number
for num in nums:
# Iterate backwards from target down to the current number.
# We go backwards to ensure we don't use the same number twice
# for the specific sum calculation in this iteration.
for i in range(target, num - 1, -1):
# Logic: Can we form sum 'i'?
# Either we could already form it (dp[i] is True), OR
# we can form it by taking the current 'num' and adding it to
# a previously found sum of 'i - num'.
if dp[i - num]:
dp[i] = True
# Optimization: If we already found the target, return True immediately
if dp[target]:
return True
return dp[target]
# --- Testing the Program ---
if __name__ == "__main__":
# Test Case 1: Can be partitioned [1, 5, 5] and [11] -> Sums are 11 and 11
nums1 = [1, 5, 11, 5]
print(f"Nums: {nums1} -> {canPartition(nums1)}") # Expected: True
# Test Case 2: Cannot be partitioned
nums2 = [1, 2, 3, 5]
print(f"Nums: {nums2} -> {canPartition(nums2)}") # Expected: False
# Test Case 3: Larger numbers
nums3 = [1, 2, 3, 4, 5, 6, 7]
# Sum is 28, Target is 14. e.g. [7, 6, 1] = 14.
print(f"Nums: {nums3} -> {canPartition(nums3)}") # Expected: True
How it Works (Detailed Walkthrough)
Let's trace nums = [1, 5, 11, 5].
- Total Sum: 1+5+11+5=22. It is even.
- Target: 11.
- Initialize
dp: [True, False, False, ..., False] (size 12).
Iteration 1: num = 1
- Update
dp from index 11 down to 1.
dp[1] becomes True (because dp[1-1] is True).
- State: Sums 0 and 1 are possible.
Iteration 2: num = 5
- Update from 11 down to 5.
dp[6] becomes True (using 1 + 5).
dp[5] becomes True (using 5).
- State: Sums 0, 1, 5, 6 are possible.
Iteration 3: num = 11
- Update from 11 down to 11.
dp[11] becomes True (because dp[11-11] which is dp[0] is True).
- We found the target! Return
True.
Complexity Analysis
- Time Complexity: O(N×S), where N is the number of elements and S is the target sum (half of total sum). We iterate through N numbers, and for each, we iterate up to .
C++ Solution (Optional)
If you prefer C++, here is the equivalent implementation using std::vector:
#include <iostream>
#include <vector>
#include <numeric> // for accumulate
bool canPartition(std::vector<int>& nums) {
int totalSum = std::accumulate(nums.begin(), nums.end(), 0);
if (totalSum % 2 != 0) return false;
int target = totalSum / 2;
std::vector<bool> dp(target + 1, false);
dp[0] = true;
for (int num : nums) {
// Must iterate backwards to avoid using the same item twice for current step
for (int i = target; i >= num; --i) {
if (dp[i - num]) {
dp[i] = true;
}
}
if (dp[target]) return true;
}
return dp[target];
}