101 Logo
onenoughtone

Code Implementation

Partition Equal Subset Sum Implementation

Below is the implementation of the partition equal subset sum:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Determine if the array can be partitioned into two subsets with equal sum.
* Dynamic Programming (2D) approach.
*
* @param {number[]} nums - Array of integers
* @return {boolean} - True if the array can be partitioned, false otherwise
*/
function canPartition(nums) {
// Calculate the total sum of the array
const totalSum = nums.reduce((sum, num) => sum + num, 0);
// If the total sum is odd, return false
if (totalSum % 2 !== 0) {
return false;
}
const target = totalSum / 2;
const n = nums.length;
// Initialize DP array
const dp = Array(n + 1).fill().map(() => Array(target + 1).fill(false));
// Base cases
dp[0][0] = true;
// Fill DP array
for (let i = 1; i <= n; i++) {
for (let j = 0; j <= target; j++) {
// Exclude the current element
dp[i][j] = dp[i - 1][j];
// Include the current element if possible
if (j >= nums[i - 1]) {
dp[i][j] = dp[i][j] || dp[i - 1][j - nums[i - 1]];
}
}
}
return dp[n][target];
}
/**
* Determine if the array can be partitioned into two subsets with equal sum.
* Dynamic Programming (1D) approach.
*
* @param {number[]} nums - Array of integers
* @return {boolean} - True if the array can be partitioned, false otherwise
*/
function canPartitionOptimized(nums) {
// Calculate the total sum of the array
const totalSum = nums.reduce((sum, num) => sum + num, 0);
// If the total sum is odd, return false
if (totalSum % 2 !== 0) {
return false;
}
const target = totalSum / 2;
// Initialize DP array
const dp = Array(target + 1).fill(false);
dp[0] = true;
// Fill DP array
for (const num of nums) {
for (let j = target; j >= num; j--) {
dp[j] = dp[j] || dp[j - num];
}
}
return dp[target];
}
// Test cases
console.log(canPartition([1, 5, 11, 5])); // true
console.log(canPartition([1, 2, 3, 5])); // false
console.log(canPartitionOptimized([1, 5, 11, 5])); // true
console.log(canPartitionOptimized([1, 2, 3, 5])); // false

Step-by-Step Explanation

Let's break down the implementation:

  1. Calculate Total Sum: Calculate the total sum of the array to determine if it's possible to partition it into two equal subsets.
  2. Check for Odd Sum: If the total sum is odd, it's impossible to partition the array into two equal subsets, so return false.
  3. Set Target Sum: Set the target sum to half of the total sum, as we need to find a subset with this sum.
  4. Initialize DP Array: Initialize a DP array to keep track of which sums are possible to achieve with the given numbers.
  5. Fill DP Array: For each number in the array, update the DP array to reflect which sums are possible to achieve.
ProblemSolutionCode
101 Logo
onenoughtone