Partition Equal Subset Sum (LeetCode 416): Solution and Explanation

Medium
Array
Dynamic Programming

Given an array of positive integers, decide whether you can split it into two groups whose sums are equal. Every number must go into exactly one of the two groups.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Start by simplifying what is being asked. If the two groups have equal sums, each must equal half of the total. So the question becomes whether some subset of the numbers adds up to exactly total / 2, and if the total is odd the answer is immediately no. Once you find one such subset, the leftover numbers automatically form the other half.

The brute force tries every subset, which is 2^n possibilities and hopeless for 200 numbers. But the values are small: each is at most 100, so the target is at most 10,000. That points to dynamic programming over sums rather than over subsets. This is the 0/1 knapsack pattern, where each item is either taken once or not at all.

Keep a boolean array dp where dp[j] means some subset of the numbers seen so far sums to j. Initially only dp[0] is true, thanks to the empty subset. When you process a new number num, any sum j becomes reachable if j - num was reachable before. The subtle part is the direction of the inner loop: iterating j from high to low ensures that dp[j - num] still reflects the state before num was added, so each number is used at most once.

Approach: 0/1 knapsack with a one-dimensional boolean DP

  1. Compute total = sum(nums). If it is odd, return False.
  2. Set target = total // 2 and create dp of length target + 1 with only dp[0] = True.
  3. For each num, loop j downward from target to num.
  4. Set dp[j] = dp[j] or dp[j - num], meaning sum j is reachable either without this number or by adding it to a reachable j - num.
  5. After all numbers are processed, return dp[target].

Step-by-step example

nums = [1,5,11,5]
  1. The total is 22, which is even, so target = 11 and only sum 0 is reachable.
  2. Processing 1 makes sum 1 reachable. The reachable set is {0, 1}.
  3. Processing 5, going downward, marks 6 (from 1) and 5 (from 0). The reachable set is {0, 1, 5, 6}.
  4. Processing 11 marks 11 from 0, so dp[11] is already True. The last 5 adds 10 (from 5) and keeps 11 reachable.
  5. dp[11] is True, so the function returns True. One valid split is [11] and [1, 5, 5].

Code: Python, Java, C++

1class Solution:
2    def canPartition(self, nums: List[int]) -> bool:
3        total = sum(nums)
4        if total % 2 != 0:
5            return False
6
7        target = total // 2
8        dp = [False] * (target + 1)
9        dp[0] = True
10
11        for num in nums:
12            for j in range(target, num - 1, -1):
13                dp[j] = dp[j] or dp[j - num]
14
15        return dp[target]

Time and space complexity

Time

O(n × target)

For each of the n numbers, the inner loop runs over at most target + 1 sums, where target is half the total. With the given limits that is at most 200 × 10,000 cell updates.

Space

O(target)

Only one boolean array of length target + 1 is kept, reused for every number.

Other approaches

Two-dimensional DP table (time O(n × target), space O(n × target))

Use dp[i][j] for whether the first i numbers can reach sum j. It is the same recurrence written out fully, which is easier to visualize but needs n times more memory.

Bitset of reachable sums (time O(n × target / w), space O(target / w))

Store reachable sums as bits of one big integer and update with bits |= bits << num, then test bit target. It performs the same knapsack with word-level parallelism and is very fast in practice.

Common mistakes

  • Looping j upward. Then dp[j - num] may already include the current number, which lets a number be reused and gives false positives such as [1, 3] appearing to reach 2.
  • Forgetting the odd-total check, which makes total // 2 round down and can report a split that does not exist.
  • Starting with dp[0] = False. Sum zero must be reachable, or nothing else can ever become true.
  • Trying a greedy approach such as sorting and filling the larger half first. It fails on many inputs because the right subset is not built from the largest values.

Frequently asked questions

Why is Partition Equal Subset Sum a knapsack problem?

It reduces to asking whether a subset of the numbers sums to exactly half of the total. Choosing each number at most once to hit an exact sum is the 0/1 knapsack, or subset sum, problem.

Why does the inner loop go backwards?

Going from high sums to low sums means dp[j - num] has not yet been updated for the current number. That guarantees each number contributes at most once; looping forward would allow it to be used repeatedly.

What is the time complexity of Partition Equal Subset Sum?

It is O(n × target), where target is half the sum. This is pseudo-polynomial, so it is fast here because the values are small, but it would not scale if the numbers could be in the billions.

Can I solve it with recursion and memoization?

Yes. Recurse on (index, remaining sum), choosing to take or skip each number, and cache results. It has the same complexity, but the bottom-up array avoids recursion depth issues.