Partition Equal Subset Sum

MediumDynamic Programming · 0/1 Knapsack🧩 Knapsack DPLeetCode #416 ↗Updated

Problem

Given an array of positive integers nums, decide whether you can split it into two groups (every element used exactly once) whose sums are equal.
Input[1,5,11,5]Outputtrue ({1,5,5} | {11})
Input[1,2,3,5]Outputfalse

1 ≤ n ≤ 200  ·  1 ≤ nums[i] ≤ 100

Try it yourself

Java
class Solution {
    public boolean canPartition(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
If the total is odd the answer is false; otherwise ask: does some subset sum to total/2? (the rest automatically makes the other half). That is a 0/1 knapsack over sums 0..total/2.
PatternKnapsack DP

Instinct Choose items to hit or stay under a target sum (can it be done, best value, fewest items, how many ways) - index a DP array by the remaining capacity.

Memory hack Once? Walk back. Many? Walk forward. Each item used at most once loops capacity downward; reusable items loop it upward.

Open the Knapsack DP guide →

Approaches

Brute ForceInclude / Exclude Recursion

Time O(2n)Space O(n)

For each index, either put nums[i] into the subset (reduce the remaining target) or leave it out. Succeed when the remaining target hits 0. Every element doubles the number of paths.

Java
public boolean canPartition(int[] nums) {
    int total = 0;
    for (int x : nums) total += x;
    if (total % 2 != 0) return false;
    return can(nums, 0, total / 2);
}
private boolean can(int[] nums, int i, int rem) {
    if (rem == 0) return true;
    if (i == nums.length || rem < 0) return false;
    return can(nums, i + 1, rem - nums[i]) || can(nums, i + 1, rem);
}

Simple, but 2200 paths in the worst case.

At a glance

LevelApproachTimeSpace
Brute ForceInclude / Exclude RecursionO(2n)O(n)
BetterMemoization on (index, remaining)O(n·S)O(n·S)
Optimal1-D Bottom-Up KnapsackO(n·S)O(S)
Common pitfalls
  • Skipping the odd-total check — total/2 silently rounds down.
  • Iterating s upwards in 1-D — reuses a number (unbounded knapsack).
  • Memoizing with primitive boolean — can't tell “false” from “unknown”.
Interview tips
  • Reduce to subset-sum first; say it out loud before coding.
  • Mention it is pseudo-polynomial: O(n·S) depends on the values, not just n.
  • Show the 2-D → 1-D compression and why the loop must go backwards.
Pattern
0/1 Knapsack (subset sum) → pick each item at most once to hit an exact capacity/sum.
My notes saved in this browser