mediumDynamic ProgrammingDynamic Programming

Partition Equal Subset Sum

mediumTime: O(n * sum)Space: O(sum)

Recognize the pattern

partition array into two subsets with equal sumsubset sum problem0/1 knapsack variant

Brute force idea

A straightforward first read of Partition Equal Subset Sum is this: Try all 2^n subsets and check if any sums to total/2. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The deeper shift in Partition Equal Subset Sum is this: DP: dp[j] = true if a subset sums to j. For each number, update dp right-to-left: dp[j] = dp[j] || dp[j - num]. Target = totalSum / 2. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Partition Equal Subset Sum is one steady idea: If any subset sums to totalSum/2, the remaining elements also sum to totalSum/2 — so we only need to find ONE subset with the target sum. This is exactly the 0/1 knapsack problem with the target as capacity. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

One easy way to drift off course in Partition Equal Subset Sum is this: Not checking if totalSum is odd — if odd, equal partition is impossible (two integers can't sum to an odd number). Return false immediately. The fix is usually to return to the meaning of each move, not just the steps themselves.

Dynamic Programming Pattern