Partition Equal Subset Sum - Problem

Given an integer array nums, determine if you can partition the array into two subsets such that the sum of elements in both subsets is exactly equal.

This is a classic problem that tests your understanding of dynamic programming and subset sum concepts. The key insight is that if we can partition an array into two equal subsets, then each subset must have a sum equal to total_sum / 2.

Goal: Return true if such a partition exists, false otherwise.

Example: For array [1, 5, 11, 5], we can partition it into [1, 5, 5] and [11], both having sum = 11.

Input & Output

example_1.py โ€” Equal Partition Possible
$ Input: nums = [1, 5, 11, 5]
โ€บ Output: true
๐Ÿ’ก Note: The array can be partitioned as [1, 5, 5] and [11], both subsets have sum = 11
example_2.py โ€” No Equal Partition
$ Input: nums = [1, 2, 3, 5]
โ€บ Output: false
๐Ÿ’ก Note: Total sum is 11 (odd), so it's impossible to partition into two equal subsets
example_3.py โ€” Single Element
$ Input: nums = [1]
โ€บ Output: false
๐Ÿ’ก Note: Cannot partition a single element into two non-empty equal subsets

Constraints

  • 1 โ‰ค nums.length โ‰ค 200
  • 1 โ‰ค nums[i] โ‰ค 100
  • All integers in nums are positive

Visualization

Tap to expand
Dynamic Programming: Subset Sum OptimizationArray: [1, 5, 11, 5] โ†’ Target: 11DP Array Progress:Initial:T0F1... F F FF11Add 1:TTF F F ...FAdd 5:TTF F FT5T6...Final:TT F F F T T F F F F FT11TARGET FOUND! โœ“๐ŸŽฏ Key InsightWe only need to track whichsums are possible, not theactual subsets themselves!Space: O(sum) instead of O(2^n)
Understanding the Visualization
1
Check Feasibility
If total sum is odd, return false immediately
2
Initialize DP
Create boolean array to track achievable sums, dp[0] = true
3
Process Each Element
For each element, update which new sums become possible
4
Return Result
Check if target sum (total/2) is achievable
Key Takeaway
๐ŸŽฏ Key Insight: Instead of generating all possible subsets (exponential), we use DP to track achievable sums in O(n ร— sum) time and O(sum) space!
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
58.3K Views
High Frequency
~25 min Avg. Time
1.8K 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