Skip to content

Commit 6d632e3

Browse files
committed
Create readme.md
1 parent 63217c6 commit 6d632e3

1 file changed

Lines changed: 74 additions & 0 deletions

File tree

  • Python_Daily_Solutions/416. Partition Equal Subset Sum
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Partition Equal Subset Sum
2+
3+
## Problem Statement
4+
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, otherwise return `false`.
5+
6+
## Examples
7+
8+
### Example 1:
9+
**Input:**
10+
```plaintext
11+
nums = [1,5,11,5]
12+
```
13+
**Output:**
14+
```plaintext
15+
true
16+
```
17+
**Explanation:**
18+
The array can be partitioned as `[1, 5, 5]` and `[11]`.
19+
20+
### Example 2:
21+
**Input:**
22+
```plaintext
23+
nums = [1,2,3,5]
24+
```
25+
**Output:**
26+
```plaintext
27+
false
28+
```
29+
**Explanation:**
30+
The array cannot be partitioned into equal sum subsets.
31+
32+
## Constraints
33+
- `1 <= nums.length <= 200`
34+
- `1 <= nums[i] <= 100`
35+
36+
## Approach
37+
The problem can be solved using **Dynamic Programming (Subset Sum Problem)**:
38+
1. Compute the total sum of the array.
39+
2. If the total sum is odd, return `false` (since it's impossible to split into two equal parts).
40+
3. Use a **0/1 Knapsack** approach to determine if a subset with sum `total_sum/2` exists.
41+
4. Use a **bottom-up DP approach** to check if we can form the required sum.
42+
43+
## Solution
44+
The solution uses a **boolean DP array** `dp[i]`, where `dp[i]` is `true` if a subset with sum `i` can be formed.
45+
- Initialize `dp[0] = true` (sum `0` is always possible).
46+
- Iterate over each number in `nums`, updating the `dp` array in reverse order.
47+
- If `dp[target]` is `true`, return `true`, otherwise return `false`.
48+
```python
49+
class Solution:
50+
def canPartition(self, nums: List[int]) -> bool:
51+
m, mod = divmod(sum(nums), 2)
52+
if mod:
53+
return False
54+
n = len(nums)
55+
f = [[False] * (m + 1) for _ in range(n + 1)]
56+
f[0][0] = True
57+
for i, x in enumerate(nums, 1):
58+
for j in range(m + 1):
59+
f[i][j] = f[i - 1][j] or (j >= x and f[i - 1][j - x])
60+
return f[n][m]
61+
```
62+
63+
## Complexity Analysis
64+
- **Time Complexity:** `O(n * sum/2)`, where `n` is the number of elements.
65+
- **Space Complexity:** `O(sum/2)`, optimized using a 1D DP array.
66+
67+
## Usage
68+
To run the solution, use the following function:
69+
```python
70+
from solution import canPartition
71+
print(canPartition([1,5,11,5])) # Output: True
72+
print(canPartition([1,2,3,5])) # Output: False
73+
```
74+

0 commit comments

Comments
 (0)