Coding Interview PatternsPartition Equal Subset Sum
MediumDynamic Programming
Partition Equal Subset Sum
Explanation & Solution
Description
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of elements in both subsets is equal, otherwise return false.
Input:nums = [1,5,11,5]
0
1
1
5
2
11
3
5
Output: true
Explanation: The array can be partitioned as [1,5,5] and [11], both summing to 11.
Constraints
1 <= nums.length <= 2001 <= nums[i] <= 100
Approach
Dynamic Programming pattern
1. Check the Total Sum
- Compute the total sum of all elements in
nums - If the total is odd, return
falseimmediately — you cannot split an odd sum into two equal integer halves
2. Define the Target
- Set
target = total / 2 - The problem reduces to: can we find a subset of
numsthat sums to exactlytarget?
3. Initialize the DP Array
- Create a boolean array
dpof sizetarget + 1, initialized tofalse - Set
dp[0] = truebecause a sum of 0 is always achievable (empty subset)
4. Process Each Number
- For each number
numinnums, iteratejfromtargetdown tonum - Update
dp[j] = dp[j] || dp[j - num]— either we already can form sumjwithout this number, or we can form it by adding this number to a subset that sums toj - num - Iterating backwards ensures each number is used at most once
5. Return the Result
dp[target]tells us whether a subset summing to exactlytargetexists- If
true, the remaining elements also sum totarget, giving an equal partition
Key Insight
- This problem is a variant of the 0/1 Knapsack problem where we check if a subset sum equals half the total
- The 1D DP with reverse iteration keeps space at O(target)
- Time complexity is **O(n * target)** where n is the array length and target is half the total sum
Visualization
Input:
Dynamic Programmingnums = [1,5,11,5]
dp
Press play to start DP animation
ComputingDependencyFilledEmpty
7 steps