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.