Partition Equal Subset SumLoading saved progress…

Partition Equal Subset Sum

Partition Equal Subset Sum (LeetCode 416) asks whether an array of non-negative integers can be divided into two groups whose sums are equal. Because the two groups must add up to the same amount, each one has to sum to exactly half of the array's total — so the question quietly turns into is there a subset that sums to half the total?, the classic subset-sum / partition problem. If the total is odd there is no whole-number half, so the answer is immediately false. You return a single boolean.

Signature

partitionEqualSubset(nums)  // nums: array of non-negative integers -> boolean

Examples

partitionEqualSubset([1, 5, 11, 5]); // true  — {11} and {1, 5, 5} both sum to 11
partitionEqualSubset([1, 2, 3, 5]);  // false — total is 11 (odd), no equal split
partitionEqualSubset([1, 1]);        // true  — {1} and {1}

Notes

  • Non-negative integersnums holds zero or more non-negative whole numbers; you do not need to handle negative values or fractions.
  • Odd total is instantly false — two equal integer subsets each sum to total / 2, so if total is odd no split can exist. Check this before doing any real work.
  • Reduces to subset-sum — once the total is even, the task is exactly find a subset summing to total / 2; whatever is left over automatically forms the matching half.
  • Returns a boolean — you report only whether a split exists, not which numbers land in each group.
  • Empty array is true — two empty subsets both sum to 0, so [] splits (vacuously) into equal halves.

FAQ

What are the time and space complexity?
The dynamic-programming solution runs in O(n * target) time and O(target) space, where n is the number of values and target is half the total sum. It is pseudo-polynomial: the cost scales with the numeric size of the sum, not just the count of numbers.
Why can you return false immediately when the total is odd?
Two equal subsets of whole numbers would each sum to total / 2. If the total is odd, that half is not a whole number, so no split can ever exist. Checking this first also avoids a fractional DP target you could not index.
Why must the inner loop run from high to low?
Scanning the capacity downward means every dp[t - num] you read still reflects the round before this number was added, so each number is used at most once. Scanning upward reuses a number and answers the unbounded-knapsack version instead, giving wrong results.
Loading editor…