1. Understand the Goal: The user wants a program to solve the "Partition Equal Subset Sum" problem.
Analyze the Problem:
Input: An array of integers (let's call it nums).
Output: A boolean (True/False or true/false) indicating whether the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Constraints: Typically, dynamic programming is the best approach here. The constraints on the values (positive vs. negative, size of numbers) matter. Usually, in this specific LeetCode-style problem, numbers are positive integers. If they include negatives, it's a different variation (though usually solvable with offsets, standard partition implies positive integers or at least finding a target sum S/2). Let's assume standard constraints: non-empty array, positive integers.
Determine the Algorithm:
Observation 1: If the total sum of the array is odd, it's impossible to split it into two equal integer sums. Return False immediately.
Observation 2: If the total sum is even, we need to find a subset of numbers that adds up to sum / 2. This is the classic "Subset Sum" problem with a target of sum / 2.
State: dp[i] = boolean, can we sum to i using a subset of the numbers seen so far?
Base case: dp[0] = True (we can always sum to 0 with an empty set).
Transition: For each number num in nums, iterate backwards through the DP array. dp[i] = dp[i] or dp[i - num].
Optimization: We can use a 1D array instead of a 2D array to save space.
Selecting the Language: Python is the most accessible language for explaining algorithms, but providing C++ or Java is also good practice. I will provide Python as the primary solution because it reads like pseudocode, and perhaps a C++ version for performance enthusiasts.
Refining the Python Implementation:
python
def canPartition(nums):
total_sum = sum(nums)
# If sum is odd, we can't partition it into two equal integer sums
if total_sum % 2 != 0:
return False
target = total_sum // 2
n = len(nums)
# dp[i] will be True if we can make sum 'i' using available numbers
dp = [False] * (target + 1)
dp[0] = True
for num in nums:
# Iterate backwards to avoid using the same number multiple times
# for the same calculation step (0/1 Knapsack property)
for i in range(target, num - 1, -1):
if dp[i - num]:
dp[i] = True
return dp[target]
Refining the C++ Implementation (for completeness):
cpp
#include <vector>
#include <numeric>
class Solution {
public:
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) {
for (int i = target; i >= num; i--) {
dp[i] = dp[i] || dp[i - num];
}
}
return dp[target];
}
};
Addressing Edge Cases:
Empty array: Sum is 0. Target is 0. Returns True (technically, empty set can be partitioned into two empty sets).
Single element: Sum is x. If x is odd, False. If x is even? Wait, if array is [2], sum=2, target=1. Cannot sum to 1 with element 2. Returns False. Correct.
Large numbers: If sum is huge, dp array will be too large. Bit manipulation (bitset) is an alternative optimization for C++, but for general purpose, standard DP is expected.
Structuring the Output:
Start with a clear explanation of the logic (Odd sum check -> Subset Sum problem).
Provide the Python code.
Provide a C++ version.
Explain the Time and Space complexity.
Reviewing the prompt: "Create a program". The user didn't specify a language. I will provide Python as the main solution but label it clearly.
Final Polish: Ensure comments in code explain why we iterate backwards (0/1 knapsack constraint).
(Self-Correction during drafting): Should I handle negative numbers?
If negatives are allowed, the target is still sum/2, but the range of possible sums shifts. To handle this in DP requires offsetting indices.
Decision: Stick to the standard positive integer assumption unless specified otherwise, but mention it briefly or stick to the standard problem definition to avoid confusion. I will assume non-negative integers as per standard definition.
Final Code Structure:
Class/Function wrapper.
Input handling (example usage).
Output display.
This looks solid. I will generate the response based on these steps.
Here is a solution in Python. This problem is a classic dynamic programming challenge that can be reduced to the Subset Sum Problem.
The Logic
Total Sum Check: First, calculate the total sum of the array. If the sum is odd, it is impossible to partition it into two equal halves, so we return False immediately.
Target: If the sum is even, our target is simply sum / 2. We just need to find if any subset of numbers adds up to this target.
Dynamic Programming: We use a boolean array dp where dp[i] is True if a sum of i can be achieved using the numbers processed so far.
Initialize dp[0] to True (a sum of 0 is always possible with an empty set).
For every number in the input array, update the dp array backwards from the target down to the number itself.
Python Solution
python
def can_partition(nums):
# 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
# The target sum for each subset
target = total_sum // 2
# Step 3: Initialize DP array
# dp[i] indicates whether a subset sum of 'i' is achievable
# We only need to track sums up to the target
dp = [False] * (target + 1)
dp[0] = True
# Step 4: 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 same specific sum calculation in this iteration.
for i in range(target, num - 1, -1):
if dp[i - num]:
dp[i] = True
# Optimization: If we hit the target early, we can return True
if dp[target]:
return True
return dp[target]
# --- Test Cases ---
if __name__ == "__main__":
# Example 1: Can be partitioned ([1, 5, 11] vs [5])
nums1 = [1, 5, 11, 5]
print(f"Input: {nums1} -> Output: {can_partition(nums1)}")
# Example 2: Cannot be partitioned
nums2 = [1, 2, 3, 5]
print(f"Input: {nums2} -> Output: {can_partition(nums2)}")
# Example 3: Edge case (empty or single item)
nums3 = [1]
print(f"Input: {nums3} -> Output: {can_partition(nums3)}")
Complexity Analysis
Time Complexity:O(N×S), where N is the number of elements in the array and S is the total sum of the array (specifically target). For every number, we potentially iterate through the DP array up to the target sum.
Space Complexity:O(S). We only use a 1D array of size to store the state, rather than a 2D matrix.
Optimization Note
This approach is efficient for cases where the sum of the numbers is reasonable. If the numbers are very large (resulting in a massive sum) but the count of numbers is small, a recursive approach with memoization (using a Hash Map/Set) might be more memory efficient, though for standard interview constraints, the DP approach above is preferred.