Partition Equal Subset Sum - Problem

Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal, or false otherwise.

Key Points:

  • Each element can only be used once
  • Both subsets must contain at least one element
  • The order of elements within subsets doesn't matter

Input & Output

Example 1 — Basic Partition
$ Input: nums = [1,5,11,5]
Output: true
💡 Note: Array can be partitioned as [1,5,5] and [11]. Both subsets have sum = 11.
Example 2 — Cannot Partition
$ Input: nums = [1,2,3,5]
Output: false
💡 Note: Total sum = 11 (odd), so cannot be split into two equal subsets.
Example 3 — Minimum Case
$ Input: nums = [1,1]
Output: true
💡 Note: Can partition as [1] and [1]. Both subsets have sum = 1.

Constraints

  • 1 ≤ nums.length ≤ 200
  • 1 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Partition Equal Subset Sum INPUT nums = [1, 5, 11, 5] 1 5 11 5 [0] [1] [2] [3] Total Sum = 22 Target = 22/2 = 11 Target: 11 Find subset with sum = 11 Each element used once Both subsets non-empty ALGORITHM (DP) 1 Check Sum If odd, return false 2 Init DP Set dp = {0} (achievable sums) 3 Process Elements Add num to each sum in dp 4 Check Target Return target in dp DP Progression: num=1: {0,1} num=5: {0,1,5,6} num=11: {0,1,5,6,11,12,16,17} num=5: {...,11,...} OK! FINAL RESULT Valid Partition Found! Subset 1 1 5 5 =11 Subset 2 11 =11 == Output: true 11 + 11 = 22 Both subsets equal! OK Key Insight: This is a variant of the 0/1 Knapsack problem. We use DP to track all achievable subset sums. If total sum is odd, partition is impossible. Otherwise, find if sum/2 is achievable. Time: O(n * sum), Space: O(sum) where sum = total/2. Using set optimizes for sparse sums. TutorialsPoint - Partition Equal Subset Sum | Dynamic Programming Approach
Asked in
Amazon 45 Google 38 Facebook 32 Microsoft 28
185.0K Views
High Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen