InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

Partition Equal Subset Sum

medium Original ↗
Solving tips
  • Reduce to subset-sum: if total is odd return False immediately, else ask whether any subset hits target = total/2.
  • This is 0/1 knapsack over a boolean reachability array dp[s], seeded dp[0]=True.
  • Iterate the inner sum loop DOWNWARD (target..num) so each number is used once; going upward solves the unbounded variant and gives false positives.
  • Target O(n*target) time, O(target) space; you can early-exit as soon as dp[target] becomes True.

Problem

Given an array nums of positive integers, decide whether it can be split into two groups whose sums are equal. Return True if such a partition exists, otherwise False. Every element must go into exactly one group.

Examples

  • nums = [1,5,11,5]True[1,5,5] and [11] both sum to 11.
  • nums = [1,2,3,5]False — total is 11, which is odd, so no equal split is possible.
  • nums = [2,2,3,5]False — total 12, but no subset sums to 6.

Constraints

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 100
  • The total sum is at most 20000.

Think about it first

Hint 1 If the two halves are equal, each must sum to total / 2. So first: if total is odd, immediately return False. Otherwise the question becomes "does some subset sum to target = total / 2?"
Hint 2 That's the classic subset-sum problem, itself a 0/1 knapsack: each element is either included or not. Define reachability over sums from 0 to target.
Hint 3 Keep a boolean set/array reachable[s] = can we hit sum s? Start with {0}. For each number, every currently reachable sum s also makes s + num reachable. Iterate sums downward if you compress to a 1-D array, so each number is used at most once.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.