416. Partition Equal Subset Sum
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks if we can partition a given array of integers nums into two subsets with equal sums. This is a classic combinatorial optimization problem.
Solution
Partition Equal Subset Sum in Python
class Solution:
def canPartition(self, nums: List[int]) -> bool:
# Calculate the total sum of the elements in the list.
total_sum = sum(nums)
# If the total sum is odd, it's impossible to partition it into two equal subsets.
if total_sum % 2 != 0:
return False
# The target sum for each subset is half of the total sum.
target = total_sum // 2
# dp[i] will be True if a subset with sum 'i' can be formed.
# Initialize a DP set to store achievable sums. Using a set can be slightly more
# efficient than a boolean list for checking existence.
# Start with 0, as an empty subset has a sum of 0.
dp = {0}
# This problem is now a 0/1 knapsack problem:
# can we find a subset that sums up to 'target'?
for num in nums:
# Create new sums by adding the current number to all existing sums in dp.
# We iterate over a copy of dp (list(dp)) to avoid modification issues during iteration.
new_sums = set()
for s in dp:
if s + num <= target:
new_sums.add(s + num)
dp.update(new_sums)
# If we have formed the target sum, we can stop early.
if target in dp:
return True
# The final answer is whether the target sum is in our set of achievable sums.
return target in dp
Partition Equal Subset Sum in Java
class Solution {
public boolean canPartition(int[] nums) {
// Calculate the total sum of the elements in the array.
int totalSum = 0;
for (int num : nums) {
totalSum += num;
}
// If the total sum is odd, it's impossible to partition it into two equal subsets.
if (totalSum % 2 != 0) {
return false;
}
// The target sum for each subset is half of the total sum.
int target = totalSum / 2;
// dp[i] will be true if a subset with sum 'i' can be formed.
boolean[] dp = new boolean[target + 1];
// Base case: a sum of 0 is always possible (with an empty subset).
dp[0] = true;
// This problem is now a 0/1 knapsack problem:
// can we find a subset that sums up to 'target'?
for (int num : nums) {
// We iterate backwards to prevent using the same element multiple times in one subset.
// If we went forwards, dp[j-num] might have been updated by the current 'num' in this same iteration.
for (int j = target; j >= num; j--) {
// A sum 'j' can be achieved if:
// 1. It was already achievable before considering the current 'num' (dp[j])
// 2. We can form sum 'j-num' and now we add 'num' to it.
dp[j] = dp[j] || dp[j - num];
}
}
// The final answer is whether a subset with sum 'target' can be formed.
return dp[target];
}
}
Partition Equal Subset Sum in C++
class Solution {
public:
bool canPartition(vector<int>& nums) {
// Calculate the total sum of the elements in the array.
int totalSum = 0;
for (int num : nums) {
totalSum += num;
}
// If the total sum is odd, it's impossible to partition it into two equal subsets.
if (totalSum % 2 != 0) {
return false;
}
// The target sum for each subset is half of the total sum.
int target = totalSum / 2;
// dp[i] will be true if a subset with sum 'i' can be formed.
vector<bool> dp(target + 1, false);
// Base case: a sum of 0 is always possible (with an empty subset).
dp[0] = true;
// This problem is now a 0/1 knapsack problem:
// can we find a subset that sums up to 'target'?
for (int num : nums) {
// We iterate backwards to prevent using the same element multiple times in one subset.
// If we went forwards, dp[j-num] might have been updated by the current 'num' in this same iteration.
for (int j = target; j >= num; --j) {
// A sum 'j' can be achieved if:
// 1. It was already achievable before considering the current 'num' (dp[j])
// 2. We can form sum 'j-num' and now we add 'num' to it.
dp[j] = dp[j] || dp[j - num];
}
}
// The final answer is whether a subset with sum 'target' can be formed.
return dp[target];
}
};
Partition Equal Subset Sum in TypeScript
function canPartition(nums: number[]): boolean {
// Calculate the total sum of the elements in the array.
let totalSum = 0;
for (const num of nums) {
totalSum += num;
}
// If the total sum is odd, it's impossible to partition it into two equal subsets.
if (totalSum % 2 !== 0) {
return false;
}
// The target sum for each subset is half of the total sum.
const target = totalSum / 2;
// dp[i] will be true if a subset with sum 'i' can be formed.
const dp: boolean[] = new Array(target + 1).fill(false);
// Base case: a sum of 0 is always possible (with an empty subset).
dp[0] = true;
// This problem is now a 0/1 knapsack problem:
// can we find a subset that sums up to 'target'?
for (const num of nums) {
// We iterate backwards to prevent using the same element multiple times in one subset.
// If we went forwards, dp[j-num] might have been updated by the current 'num' in this same iteration.
for (let j = target; j >= num; j--) {
// A sum 'j' can be achieved if:
// 1. It was already achievable before considering the current 'num' (dp[j])
// 2. We can form sum 'j-num' and now we add 'num' to it.
dp[j] = dp[j] || dp[j - num];
}
}
// The final answer is whether a subset with sum 'target' can be formed.
return dp[target];
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.