DSA AnimatorDSA animations
Partition Equal Subset Sum LC #416 Medium 0/1 Knapsack DP
Problem

Given an integer array nums, return true if you can split it into two subsets with equal sums, otherwise false. Every element goes into exactly one subset.

Example 1
Input: nums = [1,5,11,5]
Output: true ([1,5,5] and [11], both sum to 11)
Example 2
Input: nums = [1,2,3,5]
Output: false (the total 11 is odd)
Constraints: 1 ≤ nums.length ≤ 200  |  1 ≤ nums[i] ≤ 100
🪙 Coins & reachable sums
🎯
⚖️
Subset A
Subset B
🪙 current coin🎯 target = total / 2 sum is reachable (with the coins shown) just became reachable sums checked this round (right → left)
Variables
total
—
target
—
coin x
—
s ← s − x
—
💡 Step Logic
Press ▶ Play or Next to begin.
✓
Ready
0 / 0
Pick an example and press Play.
Algorithm
1
If the total is odd, return false immediately
2
target = total / 2; dp[0] = true (the empty subset)
3
For each coin x, for s = target … x (right to left): dp[s] |= dp[s − x]
4
As soon as dp[target] is true → return true 🎯
Time
O(n · target)
Space
O(target)
🧠 Why right-to-left?

With coin 2, going left-to-right would make 2 reachable, then use that same round's 2 to reach 4, then 6… that's using the coin again and again (the unbounded knapsack). Going right-to-left, every dp[s − x] you read is still from the previous coins, so each coin is used at most once: the 0/1 knapsack.

⚠️ Edge cases

Odd total → impossible, no DP needed. Even total but no subset (e.g. [2,2,3,5], target 6) → the DP finishes without lighting 🎯. One element larger than target → false straight away. A single element can never be split.

How to solve Partition Equal Subset Sum

LeetCode 416 · Medium · Dynamic Programming · Pattern: 0/1 Knapsack

Why the obvious approach is slow

Trying every subset is 2 to the power n. But only the sums matter, and they are bounded.

The key idea

If the total is odd, it is impossible. Otherwise, the question becomes: is there a subset that adds up to half the total? Keep a boolean array where reachable of s is true when some subset sums to s. For each number, update the array from high sums down to low ones. Going downwards makes sure each number is used at most once.

Remember

Equal partition means a subset with half the total. Loop sums downwards for 0 1 knapsack, so each item is used once.

Run the animation above on your own input, or watch the 1:49 video explanation of Partition Equal Subset Sum with a dry run and Java code.

More Dynamic Programming problems