416. Partition Equal Subset Sum
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- 1-D Dynamic Programming
- Time
- O(n * target)
- Space
- O(target)
Standard Solution (C++)
SummaryDecide whether an array of positive integers can be split into two groups whose sums are equal.
Approach
Key idea: Two equal halves exist only if the total sum is even and some subset sums to total/2 (a 0/1 subset-sum problem).
Steps:
- Compute the total. If it is odd, return false.
- Let target = total / 2 and use a boolean DP where dp[s] means 's' is reachable as a subset sum.
- For each number, iterate sums downward from target to num so each item is used at most once.
- Return dp[target].
class Solution {
public:
bool canPartition(vector<int>& nums) {
int total = 0;
for (int x : nums) total += x;
if (total % 2 != 0) return false;
int target = total / 2;
vector<bool> dp(target + 1, false);
dp[0] = true;
for (int num : nums) {
for (int s = target; s >= num; --s) {
if (dp[s - num]) dp[s] = true;
}
}
return dp[target];
}
}; Time O(n * target) Space O(target)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.