← Back to Algorithms, page 5

algorithms-0085 · Medium mid

Partition equal subset sum: decide whether an array of positive integers can be split into two subsets with equal sums.

A split exists exactly when some subset sums to half the total, so return False for an odd total and otherwise solve subset sum for total/2. A boolean table reach[s] updated from high to low for each number takes O(n * total) time and O(total) space. In Python a big integer used as a bitset (bits |= bits << x) does the same work very quickly.

Full answer

Problem

Given an array of positive integers, return True if it can be partitioned into two subsets with equal sums.

Example: [1, 5, 11, 5] is True (11 and 1 + 5 + 5); [1, 2, 3, 5] is False (total 11 is odd).

Constraints: 1 <= n <= 200, values from 1 to 100, so the total is at most 20,000.

Brute force

Try all 2^n subsets and check whether one sums to half the total: O(2^n * n).

Optimal approach

  1. If the total is odd, return False. Let target = total // 2.
  2. reach = [True] + [False] * target (sum 0 is always reachable with the empty subset).
  3. For each x, for s from target down to x: reach[s] |= reach[s - x]. Stop early once reach[target] is True.
  4. Return reach[target].

Bitset version: bits = 1; for each x, bits |= bits << x; check bit target.

Why it works

The two parts have equal sums exactly when one part sums to total/2, because the other part then holds the rest. After processing the first k numbers, reach[s] says whether some subset of them sums to s. Each new number either joins a subset (moving s - x to s) or not, and the downward loop makes sure each number is added at most once. The bitset shift performs that "add x to every reachable sum" step for all sums at once.

Complexity

O(n * target) time, O(target) space. The bitset version has the same bound in bit operations but processes many sums per machine word.

Code

python
import random
from itertools import product


def can_partition(nums):
    """Split into two subsets of equal sum? Equivalent to: is there a subset summing to total/2.
    Boolean 0/1 knapsack, O(n * total) time, O(total) space."""
    total = sum(nums)
    if total % 2:
        return False
    target = total // 2
    reach = [True] + [False] * target
    for x in nums:
        for s in range(target, x - 1, -1):     # downward: each number used once
            if reach[s - x]:
                reach[s] = True
        if reach[target]:
            return True
    return reach[target]


def can_partition_bitset(nums):
    """Same idea with a Python int as a bitset: bit s set means sum s is reachable."""
    total = sum(nums)
    if total % 2:
        return False
    bits = 1
    for x in nums:
        bits |= bits << x
    return bool(bits >> (total // 2) & 1)


def brute(nums):
    total = sum(nums)
    return any(2 * sum(x for x, p in zip(nums, pick) if p) == total for pick in product((0, 1), repeat=len(nums)))


if __name__ == "__main__":
    assert can_partition([1, 5, 11, 5])                 # 11 = 1 + 5 + 5
    assert not can_partition([1, 2, 3, 5])
    assert not can_partition([1]) and can_partition([]) and can_partition([2, 2])
    rng = random.Random(85)
    for _ in range(1000):
        a = [rng.randint(1, 15) for _ in range(rng.randint(0, 10))]
        assert can_partition(a) == can_partition_bitset(a) == brute(a)
    print("all tests passed")

Save as b85_partition_equal.py and run python3 b85_partition_equal.py. It prints all tests passed (Python 3.13.5).

Edge cases

Odd total (False immediately). Single element (False). Empty array (True: both parts are empty, a convention to confirm). One element larger than half the total (False). Many duplicates.

Pattern

Subset sum as 0/1 knapsack with boolean values. Related: target sum with plus and minus signs (reduce to a subset sum of (total + target) / 2), last stone weight II (closest reachable sum to total/2), and partition into k equal subsets (backtracking with pruning or bitmask DP).

python
import random
from itertools import product


def can_partition(nums):
    """Split into two subsets of equal sum? Equivalent to: is there a subset summing to total/2.
    Boolean 0/1 knapsack, O(n * total) time, O(total) space."""
    total = sum(nums)
    if total % 2:
        return False
    target = total // 2
    reach = [True] + [False] * target
    for x in nums:
        for s in range(target, x - 1, -1):     # downward: each number used once
            if reach[s - x]:
                reach[s] = True
        if reach[target]:
            return True
    return reach[target]


def can_partition_bitset(nums):
    """Same idea with a Python int as a bitset: bit s set means sum s is reachable."""
    total = sum(nums)
    if total % 2:
        return False
    bits = 1
    for x in nums:
        bits |= bits << x
    return bool(bits >> (total // 2) & 1)


def brute(nums):
    total = sum(nums)
    return any(2 * sum(x for x, p in zip(nums, pick) if p) == total for pick in product((0, 1), repeat=len(nums)))


if __name__ == "__main__":
    assert can_partition([1, 5, 11, 5])                 # 11 = 1 + 5 + 5
    assert not can_partition([1, 2, 3, 5])
    assert not can_partition([1]) and can_partition([]) and can_partition([2, 2])
    rng = random.Random(85)
    for _ in range(1000):
        a = [rng.randint(1, 15) for _ in range(rng.randint(0, 10))]
        assert can_partition(a) == can_partition_bitset(a) == brute(a)
    print("all tests passed")

Boolean downward table with early exit and a big-integer bitset, cross-checked against all subsets on random arrays.

Complexity

Time: O(n * total). Space: O(total). Pseudo-polynomial in the total; the bitset version is much faster in practice.

By level

Fresher: Explains why the question reduces to finding a subset with half the total and writes the boolean table. Handles the odd total case.

Mid: Uses the downward 1D loop, stops early, and presents the bitset version. Reduces target sum to the same problem.

Senior: Discusses meet-in-the-middle for large values with small n, k-way partitioning with bitmask DP, and pseudo-polynomial limits. Applies the idea to load balancing across two machines.

Key points

  • Reduce to subset sum of total / 2
  • Odd total means False
  • Boolean knapsack with a downward loop
  • Bitset shift handles all sums at once
  • Pseudo-polynomial

Common mistakes

  • Forgetting the odd-total check
  • Looping upward and reusing a number
  • Sorting and greedily filling one side
  • Using a set of sums that grows without bound on large inputs

Follow-ups

  • How would you split into k equal subsets?
  • How does target sum with signs reduce to this?
  • What if values are up to 10^9 but n is 30?

Tips

  • State the reduction to total/2 first
  • Explain the downward loop
  • Mention the bitset trick

Evaluation rubric

  • Correct reduction
  • Correct DP
  • Handles odd totals
  • Correct complexity