Given an array arr of n integers, return true if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal else return false.
Input: arr = [1, 10, 21, 10]
Output: True
Explanation: The array can be partitioned as [1, 10, 10] and [21].
Input: arr = [1, 2, 3, 5]
Output: False
Explanation: The array cannot be partitioned into equal sum subsets.
Input: arr = [2, 2, 1, 1]
This question is a slight modification of the problem discussed in Subset-sum equal to target. We need to partition the array(say S) into two subsets(say S1 and S2). According to the question:
From here try to find a subset in the array with target = S/2 as discussed in Subset-sum equal to target.
The idea is to generate all pssible subsets and whenever a single subsets is found whose sum is equal to the given target(S/2), simply return true. As, all the subsets needs to generated, recursion can be used to solve this problem.
So, f(ind, target) will check whether a subset exists in the array from index 0 to index 'ind' such that the sum of elements is equal to the target.
Do not include the current element in the subset: First try to find a subset without considering the current index element. For this, make a recursive call to f(ind-1,target).
Include the current element in the subset: Now try to find a subset by considering the current index element as part of subset. As the current element(arr[ind]) is included, the remaining target sum will be target - arr[ind]. Therefore, make a function call of f(ind-1,target-arr[ind]).
Note: Consider the current element in the subset only when the current element is less or equal to the target.
/*It is pseudocode and it is not tied to
any specific programming language*/
f(ind, target){
not pick = f(ind-1, target)
pick = false
if(target <= arr[ind]{
pick = f(ind-1, target - arr[ind])
}
}
/*It is pseudocode and it is not tied to
any specific programming language*/
f(ind, target){
not pick = f(ind-1, target)
pick = false
if(target <= arr[ind]{
pick = f(ind-1, target - arr[ind])
}
return (pick || not pick)
}
#include <bits/stdc++.h>
using namespace std;
class Solution{
private:
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
bool func(int ind, int target, vector<int>& arr) {
/* Base case: If the target sum is
0, we found a valid partition*/
if (target == 0)
return true;
/* Base case: If we have considered all elements
and the target is still not 0, return false*/
if (ind == 0)
return arr[0] == target;
// Exclude the current element
bool notTaken = func(ind - 1, target, arr);
/* Include the current element if
it doesn't exceed the target*/
bool taken = false;
if (arr[ind] <= target)
taken = func(ind - 1, target - arr[ind], arr);
//Return the result
return notTaken || taken;
}
public:
/* Function to check if the array can
be partitioned into two equal subsets*/
bool equalPartition(int n, vector<int>& arr) {
int totSum = 0;
// Calculate the total sum of the array
for (int i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot
be partitioned into two equal subsets*/
if (totSum % 2 == 1)
return false;
else{
int k = totSum / 2;
// Return the result
return func(n - 1, k, arr);
}
}
};
int main() {
vector<int> arr = {2, 3, 3, 3, 4, 5};
int n = arr.size();
//Create an instance of Solution class
Solution sol;
if (sol.equalPartition(n, arr))
cout << "The Array can be partitioned into two equal subsets";
else
cout << "The Array cannot be partitioned into two equal subsets";
return 0;
}
import java.util.*;
class Solution {
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
private boolean func(int ind, int target, int[] arr) {
/* Base case: If the target sum is
0, we found a valid partition*/
if (target == 0)
return true;
/* Base case: If we have considered all elements
and the target is still not 0, return false*/
if (ind == 0)
return arr[0] == target;
// Exclude the current element
boolean notTaken = func(ind - 1, target, arr);
/* Include the current element if
it doesn't exceed the target*/
boolean taken = false;
if (arr[ind] <= target)
taken = func(ind - 1, target - arr[ind], arr);
// Return the result
return notTaken || taken;
}
/* Function to check if the array can be
partitioned into two equal subsets*/
public boolean equalPartition(int n, int[] arr) {
int totSum = 0;
// Calculate the total sum of the array
for (int i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot be
partitioned into two equal subsets*/
if (totSum % 2 == 1)
return false;
else {
int k = totSum / 2;
// Return the result
return func(n - 1, k, arr);
}
}
public static void main(String[] args) {
int[] arr = {2, 3, 3, 3, 4, 5};
int n = arr.length;
// Create an instance of Solution class
Solution sol = new Solution();
if (sol.equalPartition(n, arr))
System.out.println("The Array can be partitioned into two equal subsets");
else
System.out.println("The Array cannot be partitioned into two equal subsets");
}
}
class Solution:
""" Function to check if it's possible to partition
the array into two subsets with equal sum"""
def func(self, ind, target, arr):
""" Base case: If the target sum
is 0,we found a valid partition"""
if target == 0:
return True
""" Base case: If we have considered all elements
and the target is still not 0, return false"""
if ind == 0:
return arr[0] == target
# Exclude the current element
not_taken = self.func(ind - 1, target, arr)
""" Include the current element if
it doesn't exceed the target"""
taken = False
if arr[ind] <= target:
taken = self.func(ind - 1, target - arr[ind], arr)
# Return the result
return not_taken or taken
""" Function to check if the array can be
partitioned into two equal subsets"""
def equalPartition(self, n, arr):
tot_sum = 0
# Calculate the total sum of the array
for i in range(n):
tot_sum += arr[i]
""" If the total sum is odd, it cannot be
partitioned into two equal subsets"""
if tot_sum % 2 == 1:
return False
else:
k = tot_sum // 2
# Return the result
return self.func(n - 1, k, arr)
if __name__ == "__main__":
arr = [2, 3, 3, 3, 4, 5]
n = len(arr)
# Create an instance of Solution class
sol = Solution()
if sol.equalPartition(n, arr):
print("The Array can be partitioned into two equal subsets")
else:
print("The Array cannot be partitioned into two equal subsets")
class Solution {
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
func(ind, target, arr) {
/* Base case: If the target sum
is 0, we found a valid partition*/
if (target === 0) return true;
/* Base case: If we have considered all elements
and the target is still not 0, return false*/
if (ind === 0) return arr[0] === target;
// Exclude the current element
const notTaken = this.func(ind - 1, target, arr);
/* Include the current element if
it doesn't exceed the target*/
let taken = false;
if (arr[ind] <= target) {
taken = this.func(ind - 1, target - arr[ind], arr);
}
// Return the result
return notTaken || taken;
}
/* Function to check if the array can be
partitioned into two equal subsets*/
equalPartition(n, arr) {
let totSum = 0;
// Calculate the total sum of the array
for (let i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot be
partitioned into two equal subsets*/
if (totSum % 2 === 1) return false;
else {
const k = totSum / 2;
// Return the result
return this.func(n - 1, k, arr);
}
}
}
const arr = [2, 3, 3, 3, 4, 5];
const n = arr.length;
// Create an instance of Solution class
const sol = new Solution();
if (sol.equalPartition(n, arr)) {
console.log("The Array can be partitioned into two equal subsets");
} else {
console.log("The Array cannot be partitioned into two equal subsets");
}
If we draw the recursion tree, we will see that there are overlapping subproblems. Hence the DP approaches can be applied to the recursive solution.
The dp array stores the calculations of subproblems. Initialize dp array with -1, to indicate that no subproblem has been solved yet.
#include <bits/stdc++.h>
using namespace std;
class Solution{
private:
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
bool func(int ind, int target, vector<int> &arr, vector<vector<int>> &dp) {
/* Base case: If the target sum is
0, we found a valid partition*/
if (target == 0)
return true;
/* Base case: If we have considered all elements
and the target is still not 0, return false*/
if (ind == 0)
return arr[0] == target;
/* If the result for this state
is already calculated, return it*/
if (dp[ind][target] != -1)
return dp[ind][target];
// Exclude the current element
bool notTaken = func(ind - 1, target, arr, dp);
/* Include the current element if
it doesn't exceed the target*/
bool taken = false;
if (arr[ind] <= target)
taken = func(ind - 1, target - arr[ind], arr, dp);
//Store the result and return it
return dp[ind][target] = notTaken || taken;
}
public:
/* Function to check if the array can
be partitioned into two equal subsets*/
bool equalPartition(int n, vector<int>& arr) {
int totSum = 0;
// Calculate the total sum of the array
for (int i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot
be partitioned into two equal subsets*/
if (totSum % 2 == 1)
return false;
else{
int k = totSum / 2;
/* Initialize a DP table with dimensions
n x k+1 and initialize with -1*/
vector<vector<int>> dp(n, vector<int>(k + 1, -1));
// Return the result
return func(n - 1, k, arr, dp);
}
}
};
int main() {
vector<int> arr = {2, 3, 3, 3, 4, 5};
int n = arr.size();
//Create an instance of Solution class
Solution sol;
if (sol.equalPartition(n, arr))
cout << "The Array can be partitioned into two equal subsets";
else
cout << "The Array cannot be partitioned into two equal subsets";
return 0;
}
import java.util.*;
class Solution {
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
private boolean func(int ind, int target, int[] arr, int[][] dp) {
/* Base case: If the target sum
is 0, we found a valid partition*/
if (target == 0)
return true;
/* Base case: If we have considered all elements
and the target is still not 0, return false*/
if (ind == 0)
return arr[0] == target;
/* If the result for this state is
already calculated, return it*/
if (dp[ind][target] != -1)
return dp[ind][target] == 1;
// Exclude the current element
boolean notTaken = func(ind - 1, target, arr, dp);
/* Include the current element if
it doesn't exceed the target*/
boolean taken = false;
if (arr[ind] <= target)
taken = func(ind - 1, target - arr[ind], arr, dp);
// Store the result and return it
dp[ind][target] = (notTaken || taken) ? 1 : 0;
return dp[ind][target] == 1;
}
/* Function to check if the array can
be partitioned into two equal subsets*/
public boolean equalPartition(int n, int[] arr) {
int totSum = 0;
// Calculate the total sum of the array
for (int i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot be
partitioned into two equal subsets*/
if (totSum % 2 == 1)
return false;
else {
int k = totSum / 2;
/* Initialize a DP table with dimensions
n x k+1 and initialize with -1*/
int[][] dp = new int[n][k + 1];
for (int[] row : dp)
Arrays.fill(row, -1);
// Return the result
return func(n - 1, k, arr, dp);
}
}
public static void main(String[] args) {
int[] arr = {2, 3, 3, 3, 4, 5};
int n = arr.length;
// Create an instance of Solution class
Solution sol = new Solution();
if (sol.equalPartition(n, arr))
System.out.println("The Array can be partitioned into two equal subsets");
else
System.out.println("The Array cannot be partitioned into two equal subsets");
}
}
class Solution:
""" Function to check if it's possible to partition
the array into two subsets with equal sum"""
def func(self, ind, target, arr, dp):
""" Base case: If the target sum
is 0,we found a valid partition"""
if target == 0:
return True
""" Base case: If we have considered all elements
and the target is still not 0, return false"""
if ind == 0:
return arr[0] == target
""" If the result for this state
is already calculated, return it"""
if dp[ind][target] != -1:
return dp[ind][target] == 1
# Exclude the current element
not_taken = self.func(ind - 1, target, arr, dp)
""" Include the current element if
it doesn't exceed the target"""
taken = False
if arr[ind] <= target:
taken = self.func(ind - 1, target - arr[ind], arr, dp)
# Store the result and return it
dp[ind][target] = 1 if not_taken or taken else 0
return dp[ind][target] == 1
""" Function to check if the array can be
partitioned into two equal subsets"""
def equalPartition(self, n, arr):
tot_sum = 0
# Calculate the total sum of the array
for i in range(n):
tot_sum += arr[i]
""" If the total sum is odd, it cannot be
partitioned into two equal subsets"""
if tot_sum % 2 == 1:
return False
else:
k = tot_sum // 2
""" Initialize a DP table with dimensions
n x k+1 and initialize with -1"""
dp = [[-1] * (k + 1) for _ in range(n)]
# Return the result
return self.func(n - 1, k, arr, dp)
if __name__ == "__main__":
arr = [2, 3, 3, 3, 4, 5]
n = len(arr)
# Create an instance of Solution class
sol = Solution()
if sol.equalPartition(n, arr):
print("The Array can be partitioned into two equal subsets")
else:
print("The Array cannot be partitioned into two equal subsets")
class Solution {
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
func(ind, target, arr, dp) {
/* Base case: If the target sum
is 0, we found a valid partition*/
if (target === 0) return true;
/* Base case: If we have considered all elements
and the target is still not 0, return false*/
if (ind === 0) return arr[0] === target;
/* If the result for this state
is already calculated, return it*/
if (dp[ind][target] !== -1) return dp[ind][target] === 1;
// Exclude the current element
const notTaken = this.func(ind - 1, target, arr, dp);
/* Include the current element if
it doesn't exceed the target*/
let taken = false;
if (arr[ind] <= target) {
taken = this.func(ind - 1, target - arr[ind], arr, dp);
}
// Store the result and return it
dp[ind][target] = (notTaken || taken) ? 1 : 0;
return dp[ind][target] === 1;
}
/* Function to check if the array can be
partitioned into two equal subsets*/
equalPartition(n, arr) {
let totSum = 0;
// Calculate the total sum of the array
for (let i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot be
partitioned into two equal subsets*/
if (totSum % 2 === 1) return false;
else {
const k = totSum / 2;
/* Initialize a DP table with dimensions
n x k+1 and initialize with -1*/
const dp = Array.from({ length: n }, () => Array(k + 1).fill(-1));
// Return the result
return this.func(n - 1, k, arr, dp);
}
}
}
const arr = [2, 3, 3, 3, 4, 5];
const n = arr.length;
// Create an instance of Solution class
const sol = new Solution();
if (sol.equalPartition(n, arr)) {
console.log("The Array can be partitioned into two equal subsets");
} else {
console.log("The Array cannot be partitioned into two equal subsets");
}
In order to convert a recursive code to tabulation code, we try to convert the recursive code to tabulation and here are the steps:
The first row dp[0][] indicates that only the first element of the array is considered, therefore for the target value equal to arr[0], only cell with that target will be true, so explicitly set dp[0][arr[0]] =true, (dp[0][arr[0]] means that we are considering the first element of the array with the target equal to the first element itself). Please note that it can happen that arr[0]>target, so we first check it: if(arr[0]<=target) then set dp[0][arr[0]] = true.
#include <bits/stdc++.h>
using namespace std;
class Solution{
private:
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
bool func(int ind, int target, int n, vector<int> &arr) {
int totSum = 0;
// Calculate the total sum of the array
for (int i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot
be partitioned into two equal subsets*/
if (totSum % 2 == 1)
return false;
else {
int k = totSum / 2;
/* Create a DP table with dimensions
n x k+1, initialized with false*/
vector<vector<bool>> dp(n, vector<bool>(k + 1, false));
/* Base case: If the target sum is 0, it
can be achieved by not selecting any elements*/
for (int i = 0; i < n; i++) {
dp[i][0] = true;
}
/* Initialize the first row based
on the first element of the array*/
if (arr[0] <= k)
dp[0][arr[0]] = true;
// Fill in the DP table using bottom-up approach
for (int ind = 1; ind < n; ind++) {
for (int target = 1; target <= k; target++) {
// Exclude the current element
bool notTaken = dp[ind - 1][target];
/* Include the current element if
it doesn't exceed the target*/
bool taken = false;
if (arr[ind] <= target)
taken = dp[ind - 1][target - arr[ind]];
// Update the DP table
dp[ind][target] = notTaken || taken;
}
}
/* The final result is in
the last cell of the DP table*/
return dp[n - 1][k];
}
}
public:
/* Function to check if the array can
be partitioned into two equal subsets*/
bool equalPartition(int n, vector<int>& arr) {
int totSum = 0;
// Calculate the total sum of the array
for (int i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot
be partitioned into two equal subsets*/
if (totSum % 2 == 1)
return false;
else{
int k = totSum / 2;
// Return the result
return func(n - 1, k, n, arr);
}
}
};
int main() {
vector<int> arr = {2, 3, 3, 3, 4, 5};
int n = arr.size();
//Create an instance of Solution class
Solution sol;
if (sol.equalPartition(n, arr))
cout << "The Array can be partitioned into two equal subsets";
else
cout << "The Array cannot be partitioned into two equal subsets";
return 0;
}
import java.util.*;
class Solution {
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
private boolean func(int ind, int target, int n, int[] arr) {
int totSum = 0;
// Calculate the total sum of the array
for (int i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot
be partitioned into two equal subsets*/
if (totSum % 2 == 1)
return false;
else {
int k = totSum / 2;
/* Create a DP table with dimensions
n x k+1, initialized with false*/
boolean[][] dp = new boolean[n][k + 1];
/* Base case: If the target sum is 0, it can
be achieved by not selecting any elements*/
for (int i = 0; i < n; i++) {
dp[i][0] = true;
}
/* Initialize the first row based
on the first element of the array*/
if (arr[0] <= k)
dp[0][arr[0]] = true;
// Fill in the DP table using bottom-up approach
for (int i = 1; i < n; i++) {
for (int targetVal = 1; targetVal <= k; targetVal++) {
// Exclude the current element
boolean notTaken = dp[i - 1][targetVal];
/* Include the current element
if it doesn't exceed the target*/
boolean taken = false;
if (arr[i] <= targetVal)
taken = dp[i - 1][targetVal - arr[i]];
// Update the DP table
dp[i][targetVal] = notTaken || taken;
}
}
/* The final result is in the
last cell of the DP table*/
return dp[n - 1][k];
}
}
/* Function to check if the array can
be partitioned into two equal subsets*/
public boolean equalPartition(int n, int[] arr) {
int totSum = 0;
// Calculate the total sum of the array
for (int i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot
be partitioned into two equal subsets*/
if (totSum % 2 == 1)
return false;
else {
int k = totSum / 2;
// Return the result
return func(n - 1, k, n, arr);
}
}
public static void main(String[] args) {
int[] arr = {2, 3, 3, 3, 4, 5};
int n = arr.length;
// Create an instance of Solution class
Solution sol = new Solution();
if (sol.equalPartition(n, arr))
System.out.println("The Array can be partitioned into two equal subsets");
else
System.out.println("The Array cannot be partitioned into two equal subsets");
}
}
class Solution:
""" Function to check if it's possible to partition
the array into two subsets with equal sum"""
def func(self, ind, target, n, arr):
tot_sum = 0
# Calculate the total sum of the array
for i in range(n):
tot_sum += arr[i]
""" If the total sum is odd, it cannot
be partitioned into two equal subsets"""
if tot_sum % 2 == 1:
return False
else:
k = tot_sum // 2
""" Create a DP table with dimensions
n x k+1, initialized with False"""
dp = [[False] * (k + 1) for _ in range(n)]
""" Base case: If the target sum is 0, it can
be achieved by not selecting any elements"""
for i in range(n):
dp[i][0] = True
""" Initialize the first row based
on the first element of the array"""
if arr[0] <= k:
dp[0][arr[0]] = True
# Fill in the DP table using bottom-up approach
for i in range(1, n):
for target_val in range(1, k + 1):
# Exclude the current element
not_taken = dp[i - 1][target_val]
""" Include the current element
if it doesn't exceed the target"""
taken = False
if arr[i] <= target_val:
taken = dp[i - 1][target_val - arr[i]]
# Update the DP table
dp[i][target_val] = not_taken or taken
""" The final result is in the
last cell of the DP table"""
return dp[n - 1][k]
""" Function to check if the array can
be partitioned into two equal subsets"""
def equalPartition(self, n, arr):
tot_sum = 0
# Calculate the total sum of the array
for i in range(n):
tot_sum += arr[i]
""" If the total sum is odd, it cannot
be partitioned into two equal subsets"""
if tot_sum % 2 == 1:
return False
else:
k = tot_sum // 2
# Return the result
return self.func(n - 1, k, n, arr)
if __name__ == "__main__":
arr = [2, 3, 3, 3, 4, 5]
n = len(arr)
# Create an instance of Solution class
sol = Solution()
if sol.equalPartition(n, arr):
print("The Array can be partitioned into two equal subsets")
else:
print("The Array cannot be partitioned into two equal subsets")
class Solution {
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
func(ind, target, n, arr) {
let totSum = 0;
// Calculate the total sum of the array
for (let i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot be
partitioned into two equal subsets*/
if (totSum % 2 === 1)
return false;
else {
const k = Math.floor(totSum / 2);
/* Create a DP table with dimensions
n x k+1, initialized with false*/
const dp = Array.from({ length: n }, () => Array(k + 1).fill(false));
/* Base case: If the target sum is 0, it can
be achieved by not selecting any elements*/
for (let i = 0; i < n; i++) {
dp[i][0] = true;
}
/* Initialize the first row based
on the first element of the array*/
if (arr[0] <= k)
dp[0][arr[0]] = true;
// Fill in the DP table using bottom-up approach
for (let i = 1; i < n; i++) {
for (let targetVal = 1; targetVal <= k; targetVal++) {
// Exclude the current element
const notTaken = dp[i - 1][targetVal];
/* Include the current element
if it doesn't exceed the target*/
let taken = false;
if (arr[i] <= targetVal)
taken = dp[i - 1][targetVal - arr[i]];
// Update the DP table
dp[i][targetVal] = notTaken || taken;
}
}
/* The final result is in
the last cell of the DP table*/
return dp[n - 1][k];
}
}
/* Function to check if the array can
be partitioned into two equal subsets*/
equalPartition(n, arr) {
let totSum = 0;
// Calculate the total sum of the array
for (let i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot
be partitioned into two equal subsets*/
if (totSum % 2 === 1)
return false;
else {
const k = Math.floor(totSum / 2);
// Return the result
return this.func(n - 1, k, n, arr);
}
}
}
const arr = [2, 3, 3, 3, 4, 5];
const n = arr.length;
// Create an instance of Solution class
const sol = new Solution();
if (sol.equalPartition(n, arr)) {
console.log("The Array can be partitioned into two equal subsets");
} else {
console.log("The Array cannot be partitioned into two equal subsets");
}
#include <bits/stdc++.h>
using namespace std;
class Solution{
private:
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
bool func(int n, vector<int> &arr) {
int totSum = 0;
// Calculate the total sum of the array
for (int i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot
be partitioned into two equal subsets*/
if (totSum % 2 == 1)
return false;
else {
int k = totSum / 2;
/* Create a vector to represent
the previous row of the DP table*/
vector<bool> prev(k + 1, false);
/* Base case: If the target sum is 0, it can
be achieved by not selecting any elements*/
prev[0] = true;
/* Initialize the first row based
on the first element of the array*/
if (arr[0] <= k)
prev[arr[0]] = true;
/* Fill in the DP table
using a bottom-up approach*/
for (int ind = 1; ind < n; ind++) {
/* Initialize a vector to represent
the current row of the DP table*/
vector<bool> cur(k + 1, false);
cur[0] = true;
for (int target = 1; target <= k; target++) {
// Exclude the current element
bool notTaken = prev[target];
/* Include the current element
if it doesn't exceed the target*/
bool taken = false;
if (arr[ind] <= target)
taken = prev[target - arr[ind]];
// Update the current row of the DP table
cur[target] = notTaken || taken;
}
/* Set the current row as the
previous row for the next iteration*/
prev = cur;
}
/* The final result is in the last cell
of the previous row of the DP table*/
return prev[k];
}
}
public:
/* Function to check if the array can
be partitioned into two equal subsets*/
bool equalPartition(int n, vector<int>& arr) {
// Return the result
return func(n, arr);
}
};
int main() {
vector<int> arr = {2, 3, 3, 3, 4, 5};
int n = arr.size();
//Create an instance of Solution class
Solution sol;
if (sol.equalPartition(n, arr))
cout << "The Array can be partitioned into two equal subsets";
else
cout << "The Array cannot be partitioned into two equal subsets";
return 0;
}
import java.util.*;
class Solution {
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
private boolean func(int n, int[] arr) {
int totSum = 0;
// Calculate the total sum of the array
for (int i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot
be partitioned into two equal subsets*/
if (totSum % 2 == 1)
return false;
else {
int k = totSum / 2;
/* Initialize a vector to represent
the previous row of the DP table*/
boolean[] prev = new boolean[k + 1];
prev[0] = true;
/* Initialize the first row based
on the first element of the array*/
if (arr[0] <= k)
prev[arr[0]] = true;
// Fill in the DP table using a bottom-up approach
for (int ind = 1; ind < n; ind++) {
/* Initialize a vector to represent
the current row of the DP table*/
boolean[] cur = new boolean[k + 1];
cur[0] = true;
for (int target = 1; target <= k; target++) {
// Exclude the current element
boolean notTaken = prev[target];
/* Include the current element
if it doesn't exceed the target*/
boolean taken = false;
if (arr[ind] <= target)
taken = prev[target - arr[ind]];
// Update the current row of the DP table
cur[target] = notTaken || taken;
}
/* Set the current row as the
previous row for the next iteration*/
prev = cur;
}
/* The final result is in the last cell
of the previous row of the DP table*/
return prev[k];
}
}
/* Function to check if the array can
be partitioned into two equal subsets*/
public boolean equalPartition(int n, int[] arr) {
// Return the result
return func(n, arr);
}
public static void main(String[] args) {
int[] arr = {2, 3, 3, 3, 4, 5};
int n = arr.length;
// Create an instance of Solution class
Solution sol = new Solution();
if (sol.equalPartition(n, arr))
System.out.println("The Array can be partitioned into two equal subsets");
else
System.out.println("The Array cannot be partitioned into two equal subsets");
}
}
class Solution:
""" Function to check if it's possible to partition
the array into two subsets with equal sum"""
def func(self, n, arr):
tot_sum = 0
# Calculate the total sum of the array
for i in range(n):
tot_sum += arr[i]
""" If the total sum is odd, it cannot
be partitioned into two equal subsets"""
if tot_sum % 2 == 1:
return False
else:
k = tot_sum // 2
""" Initialize a vector to represent the
previous row of the DP table"""
prev = [False] * (k + 1)
prev[0] = True
""" Initialize the first row based
on the first element of the array"""
if arr[0] <= k:
prev[arr[0]] = True
# Fill in the DP table using a bottom-up approach
for ind in range(1, n):
""" Initialize a vector to represent
the current row of the DP table"""
cur = [False] * (k + 1)
cur[0] = True
for target in range(1, k + 1):
# Exclude the current element
not_taken = prev[target]
""" Include the current element
if it doesn't exceed the target"""
taken = False
if arr[ind] <= target:
taken = prev[target - arr[ind]]
# Update the current row of the DP table
cur[target] = not_taken or taken
""" Set the current row as the
previous row for the next iteration"""
prev = cur
""" The final result is in the last cell
of the previous row of the DP table"""
return prev[k]
""" Function to check if the array can
be partitioned into two equal subsets"""
def equalPartition(self, n, arr):
# Return the result
return self.func(n, arr)
if __name__ == "__main__":
arr = [2, 3, 3, 3, 4, 5]
n = len(arr)
# Create an instance of Solution class
sol = Solution()
if sol.equalPartition(n, arr):
print("The Array can be partitioned into two equal subsets")
else:
print("The Array cannot be partitioned into two equal subsets")
class Solution {
/* Function to check if it's possible to partition
the array into two subsets with equal sum*/
func(n, arr) {
let totSum = 0;
// Calculate the total sum of the array
for (let i = 0; i < n; i++) {
totSum += arr[i];
}
/* If the total sum is odd, it cannot
be partitioned into two equal subsets*/
if (totSum % 2 === 1)
return false;
else {
const k = Math.floor(totSum / 2);
/* Initialize a vector to represent
the previous row of the DP table*/
let prev = new Array(k + 1).fill(false);
prev[0] = true;
/* Initialize the first row based
on the first element of the array*/
if (arr[0] <= k)
prev[arr[0]] = true;
// Fill in the DP table using a bottom-up approach
for (let ind = 1; ind < n; ind++) {
/* Initialize a vector to represent
the current row of the DP table*/
let cur = new Array(k + 1).fill(false);
cur[0] = true;
for (let target = 1; target <= k; target++) {
// Exclude the current element
let notTaken = prev[target];
/* Include the current element
if it doesn't exceed the target*/
let taken = false;
if (arr[ind] <= target)
taken = prev[target - arr[ind]];
// Update the current row of the DP table
cur[target] = notTaken || taken;
}
/* Set the current row as the
previous row for the next iteration*/
prev = cur;
}
/* The final result is in the last cell
of the previous row of the DP table*/
return prev[k];
}
}
/* Function to check if the array can
be partitioned into two equal subsets*/
equalPartition(n, arr) {
// Return the result
return this.func(n, arr);
}
}
const arr = [2, 3, 3, 3, 4, 5];
const n = arr.length;
// Create an instance of Solution class
const sol = new Solution();
if (sol.equalPartition(n, arr)) {
console.log("The Array can be partitioned into two equal subsets");
} else {
console.log("The Array cannot be partitioned into two equal subsets");
}
Q: Why do we check sum(arr) % 2 == 0 first?
A: If the total sum is odd, it is impossible to split into two equal subsets.
Q: What if we wanted to partition into subsets such that their sums differ by at most d?
A: Use a modified DP approach tracking sums within the [S/2 - d, S/2 + d] range.
Q: How would you modify this problem to return the actual partitions instead of just True/False?
A: Modify the DP table to store which elements contributed to each subset, then backtrack to reconstruct the subsets.
Q: How would you solve this problem using bit manipulation?
A: Use a bitset DP, where dp |= (dp << arr[i]) efficiently computes all possible subset sums.