Ecommet

Partition Equal Subset Sum

Medium Problem 124 of 151 Java and Python

Problem

Given an array of positive integers nums, return true if it can be split into two subsets with equal sums.

Example 1

Input
nums = [1, 5, 11, 5]
Output
true
Why
[1, 5, 5] and [11].

Example 2

Input
nums = [1, 2, 3, 5]
Output
false

Constraints

  • 1 ≤ nums.length ≤ 200
  • 1 ≤ nums[i] ≤ 100

Explanation

If the total is odd, it is impossible. Otherwise the question becomes: is there a subset that sums to exactly total / 2? That is the classic 0/1 knapsack.

Keep a boolean array can[s] (some subset sums to s). For each number, update sums from high to low so the number is used at most once.

Approach 1 · Naive

Recursion: take or skip

  • Time O(2ⁿ)
  • Space O(n)

For each number, either put it in the target subset or not, and check whether total / 2 can be reached.

  1. If the total is odd, return false.
  2. can(i, remaining): true if remaining == 0; false past the end or below 0.
  3. Return can(i + 1, remaining - nums[i]) || can(i + 1, remaining).
Java
class Solution {
    public boolean canPartition(int[] nums) {
        int total = 0;
        for (int num : nums) {
            total += num;
        }
        return total % 2 == 0 && can(nums, 0, total / 2);
    }

    private boolean can(int[] nums, int i, int remaining) {
        if (remaining == 0) {
            return true;
        }
        if (i == nums.length || remaining < 0) {
            return false;
        }
        return can(nums, i + 1, remaining - nums[i]) || can(nums, i + 1, remaining);
    }
}
Python
class Solution:
    def canPartition(self, nums: List[int]) -> bool:
        total = sum(nums)
        if total % 2:
            return False

        def can(i, remaining):
            if remaining == 0:
                return True
            if i == len(nums) or remaining < 0:
                return False
            return can(i + 1, remaining - nums[i]) or can(i + 1, remaining)

        return can(0, total // 2)

Approach 2 · Optimal

0/1 knapsack over sums

  • Time O(n · target)
  • Space O(target)

Track which sums up to total / 2 are reachable, adding one number at a time.

  1. If the total is odd, return false. Let target = total / 2.
  2. can[0] = true.
  3. For each number x, for s from target down to x: can[s] |= can[s - x].
  4. Return can[target].
Java
class Solution {
    public boolean canPartition(int[] nums) {
        int total = 0;
        for (int num : nums) {
            total += num;
        }
        if (total % 2 == 1) {
            return false;
        }
        int target = total / 2;
        boolean[] can = new boolean[target + 1];
        can[0] = true;
        for (int x : nums) {
            for (int s = target; s >= x; s--) {
                can[s] = can[s] || can[s - x];
            }
        }
        return can[target];
    }
}
Python
class Solution:
    def canPartition(self, nums: List[int]) -> bool:
        total = sum(nums)
        if total % 2:
            return False
        target = total // 2
        can = [True] + [False] * target
        for x in nums:
            for s in range(target, x - 1, -1):
                can[s] = can[s] or can[s - x]
        return can[target]

Complexity compared

ApproachTimeSpace
Naive Recursion: take or skipO(2ⁿ)O(n)
Optimal 0/1 knapsack over sumsO(n · target)O(target)

Key takeaways

  • Loop the sums downwards for 0/1 knapsack (each item once); upwards would let an item be reused (unbounded knapsack).

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem