Skip to content
DSA Patterns
Menu
Language
Knapsack & Subset DPLC #4161 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Partition Equal Subset Sum

Problem (restated)

Can the array be partitioned into two subsets with equal sum?

Intuition

If total odd impossible; else subset sum to total/2 via 0/1 knapsack bool DP.

Approaches

0/1 subset sum DP

Unverified
Time O(n*sum)Space O(sum)

Idea. dp[c] |= dp[c-x] iterating capacity downward.

Walkthrough. [1,5,11,5] → true (11 vs 1+5+5).

Trade-offs. Pseudo-polynomial in sum.

Solution
export function canPartition(nums: number[]): boolean {
  const sum = nums.reduce((a, b) => a + b, 0);
  if (sum % 2) return false;
  const target = sum / 2;
  const dp = new Array<boolean>(target + 1).fill(false);
  dp[0] = true;
  for (const x of nums) {
    for (let c = target; c >= x; c--) dp[c] = dp[c]! || dp[c - x]!;
  }
  return dp[target]!;
}
export function canPartition(nums: number[]): boolean {
  const sum = nums.reduce((a, b) => a + b, 0);
  if (sum % 2) return false;
  const target = sum / 2;
  const dp = new Array<boolean>(target + 1).fill(false);
  dp[0] = true;
  for (const x of nums) {
    for (let c = target; c >= x; c--) dp[c] = dp[c]! || dp[c - x]!;
  }
  return dp[target]!;
}

Template connection

The target is sum / 2. An odd sum cannot split. For each number, walk capacity downward: dp[c] |= dp[c - x]. dp[target] is the answer.

Reflection

  • An odd total is false. The target is half the total. Each number is used once, so the inner loop walks the capacity backward.
  • A forward loop spends the same number twice. dp[0] is true: the empty subset sums to 0.
  • One element cannot be split in half. Two equal numbers are true. An empty array has total 0, so it is true.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Partition [1,5,11,5]. Sum=22, even, so ask: is subset sum 11 reachable?

1
0
5
1
11
2
5
3

target = sum/2 = 11

Key:MatchSettled