SDE & MLE Prep

416. Partition Equal Subset Sum

Problem

Decide whether nums (positive integers) can be split into two subsets with equal sums.

Example: [1,5,11,5] → true ([1,5,5] and [11]); [1,2,3,5] → false

Constraints: n ≤ 200; values ≤ 100.

Need a subset summing to total / 2. 0/1 knapsack over reachable sums: iterate the sum downward so each number is used once. (Python bitset trick: bits |= bits << x.)

Complexity: O(n · total/2).

class Solution:
    def canPartition(self, nums: List[int]) -> bool:
        total = sum(nums)
        if total % 2:
            return False
        target = total // 2
        dp = [True] + [False] * target
        for x in nums:
            for s in range(target, x - 1, -1):
                dp[s] = dp[s] or dp[s - x]
        return dp[target]