#416
Partition Equal Subset Sum
MediumArrayDynamic ProgrammingDynamic ProgrammingSubset Sum Problem
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(2^n) | O(n * target) |
| Space | O(n) | O(target) |
💡
Intuition
Time O(n * target)Space O(target)
The optimal approach uses dynamic programming to build a table that tracks whether a subset sum can be achieved for each possible sum up to half of the total. It's like filling a backpack with items to reach a specific weight without exceeding it.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the total sum of the array. If it's odd, return false.
- 2Step 2: Create a boolean DP array of size (target + 1) initialized to false, with DP[0] = true (0 sum is always achievable).
- 3Step 3: Iterate through each number in the array and update the DP array from back to front to avoid overwriting results from the current iteration.
- 4Step 4: Return the value of DP[target] which indicates if the target sum can be achieved.
solution.py11 lines
1def canPartition(nums):
2 total = sum(nums)
3 if total % 2 != 0:
4 return False
5 target = total // 2
6 dp = [False] * (target + 1)
7 dp[0] = True
8 for num in nums:
9 for i in range(target, num - 1, -1):
10 dp[i] = dp[i] or dp[i - num]
11 return dp[target]ℹ
Complexity note: This complexity comes from iterating through the array and the target sum, leading to a more manageable polynomial time complexity.
- 1The total sum must be even for a partition to be possible.
- 2Dynamic programming can significantly reduce the time complexity from exponential to polynomial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.