LeetCode 416: Partition Equal Subset Sum Solution
Master LeetCode problem 416 (Partition Equal Subset Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
416. Partition Equal Subset Sum
Problem Explanation
Explanation
To solve this problem, we can use dynamic programming. We need to find if there exists a subset of the given array whose sum is half of the total sum of the array. If such a subset exists, then it means the array can be partitioned into two subsets with equal sum.
We can create a 1D boolean array dp, where dp[i] represents whether it is possible to form a subset with sum i. We initialize dp[0] as true, since it is always possible to form a subset with sum 0. Then, for each element in the array, we update the dp array from right to left, marking all sums j as true if dp[j - nums[i]] is true.
Finally, we return dp[totalSum / 2], where totalSum is the sum of all elements in the array.
Time Complexity
The time complexity of this solution is O(n * sum), where n is the number of elements in the array and sum is the total sum of the array.
Space Complexity
The space complexity of this solution is O(sum), where sum is the total sum of the array.
Solution Code
class Solution {
public boolean canPartition(int[] nums) {
int totalSum = 0;
for (int num : nums) {
totalSum += num;
}
if (totalSum % 2 != 0) {
return false;
}
int halfSum = totalSum / 2;
boolean[] dp = new boolean[halfSum + 1];
dp[0] = true;
for (int num : nums) {
for (int j = halfSum; j >= num; j--) {
dp[j] = dp[j] || dp[j - num];
}
}
return dp[halfSum];
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 416 (Partition Equal Subset Sum)?
This page provides optimized solutions for LeetCode problem 416 (Partition Equal Subset Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 416 (Partition Equal Subset Sum)?
The time complexity for LeetCode 416 (Partition Equal Subset Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 416 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 416 in Java, C++, or Python.