Partition a Set into Two Subsets of Equal Sum
Given an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same.
Note: Each element is present in either the first subset or the second subset, but not in both.
Examples:
Input: arr[] = [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11]Input: arr[] = [1, 5, 3]
Output: false
Explanation: The array cannot be partitioned into equal sum sets.
Table of Content
- [Naive Approach] Using Recursion - O(2^n) Time and O(n) Space
- [Better Approach 1] Using Top-Down DP (Memoization) - O(sum*n) Time and O(sum*n) Space
- [Better Approach 2] Using Bottom-Up DP (Tabulation) - O(sum*n) Time and O(sum*n) Space
- [Expected Approach] Using Space Optimized DP - O(sum*n) Time and O(sum) Space
The following are the two main steps to solve this problem:
- Calculate the sum of the array. If the sum is odd, this cannot be two subsets with an equal sum, so return false.
- If the sum of the array elements is even, calculate sum/2 and find a subset of the array with a sum equal to sum/2.
The first step is simple. The second step is crucial, it can be solved either using recursion or Dynamic Programming.
[Naive Approach] Using Recursion - O(2^n) Time and O(n) Space
Let isSubsetSum(arr, n, sum/2) be the function that returns true if there is a subset of arr[0..n-1] with sum equal to sum/2
The isSubsetSum problem can be divided into two subproblems
- isSubsetSum() without considering last element (reducing n to n-1)
- isSubsetSum() considering the last element (reducing sum/2 by arr[n-1] and n to n-1)
If any of the above subproblems return true, then return true.
isSubsetSum (arr, n, sum/2) = isSubsetSum (arr, n-1, sum/2) OR isSubsetSum (arr, n-1, sum/2 - arr[n-1])
Step by Step implementation:
- First, check if the sum of the elements is even or not.
- After checking, call the recursive function isSubsetSum with parameters as input array, array size, and sum/2
- If the sum is equal to zero then return true (Base case)
- If n is equal to 0 and sum is not equal to zero then return false (Base case)
- Check if the value of the last element is greater than the remaining sum then call this function again by removing the last element
- Else call this function again for both the cases stated above and return true, if anyone of them returns true
- Print the answer
// C++ program to partition a Set
// into Two Subsets of Equal Sum
// using recursion
#include <bits/stdc++.h>
using namespace std;
// A utility function that returns true if there is
// a subset of arr[] with sum equal to given sum
bool isSubsetSum(int n, vector<int>& arr, int sum) {
// base cases
if (sum == 0)
return true;
if (n == 0)
return false;
// If element is greater than sum, then ignore it
if (arr[n-1] > sum)
return isSubsetSum(n-1, arr, sum);
// Check if sum can be obtained by any of the following
// (a) including the current element
// (b) excluding the current element
return isSubsetSum(n-1, arr, sum) ||
isSubsetSum(n-1, arr, sum - arr[n-1]);
}
// Returns true if arr[] can be partitioned in two
// subsets of equal sum, otherwise false
bool equalPartition(vector<int>& arr) {
// Calculate sum of the elements in array
int sum = accumulate(arr.begin(), arr.end(), 0);
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
// Find if there is subset with sum equal
// to half of total sum
return isSubsetSum(arr.size(), arr, sum / 2);
}
int main() {
vector<int> arr = { 1, 5, 11, 5};
if (equalPartition(arr)) {
cout << "True" << endl;
}else{
cout << "False" << endl;
}
return 0;
}
// Java program to partition a Set
// into Two Subsets of Equal Sum
// using recursion
class GfG {
static boolean isSubsetSum(int n, int[] arr, int sum) {
// base cases
if (sum == 0)
return true;
if (n == 0)
return false;
// If element is greater than sum, then ignore it
if (arr[n - 1] > sum)
return isSubsetSum(n - 1, arr, sum);
// Check if sum can be obtained by any of the following
// (a) including the current element
// (b) excluding the current element
return isSubsetSum(n - 1, arr, sum) ||
isSubsetSum(n - 1, arr, sum - arr[n - 1]);
}
static boolean equalPartition(int[] arr) {
// Calculate sum of the elements in array
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
// Find if there is subset with sum equal
// to half of total sum
return isSubsetSum(arr.length, arr, sum / 2);
}
public static void main(String[] args) {
int[] arr = { 1, 5, 11, 5 };
if (equalPartition(arr)) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
# Python program to partition a Set
# into Two Subsets of Equal Sum
# using recursion
def isSubsetSum(n, arr, sum):
# base cases
if sum == 0:
return True
if n == 0:
return False
# If element is greater than sum, then ignore it
if arr[n-1] > sum:
return isSubsetSum(n-1, arr, sum)
# Check if sum can be obtained by any of the following
# (a) including the current element
# (b) excluding the current element
return isSubsetSum(n-1, arr, sum) or \
isSubsetSum(n-1, arr, sum - arr[n-1])
def equalPartition(arr):
# Calculate sum of the elements in array
arrSum = sum(arr)
# If sum is odd, there cannot be two
# subsets with equal sum
if arrSum % 2 != 0:
return False
# Find if there is subset with sum equal
# to half of total sum
return isSubsetSum(len(arr), arr, arrSum // 2)
if __name__ == "__main__":
arr = [1, 5, 11, 5]
if equalPartition(arr):
print("True")
else:
print("False")
// C# program to partition a Set
// into Two Subsets of Equal Sum
// using recursion
using System;
class GfG {
static bool isSubsetSum(int n, int[] arr, int sum) {
// base cases
if (sum == 0)
return true;
if (n == 0)
return false;
// If element is greater than sum,
// then ignore it
if (arr[n - 1] > sum)
return isSubsetSum(n - 1, arr, sum);
// Check if sum can be obtained by any of the following
// (a) including the current element
// (b) excluding the current element
return isSubsetSum(n - 1, arr, sum) ||
isSubsetSum(n - 1, arr, sum - arr[n - 1]);
}
static bool equalPartition(int[] arr) {
// Calculate sum of the elements in array
int sum = 0;
foreach (int num in arr) {
sum += num;
}
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
// Find if there is subset with sum equal
// to half of total sum
return isSubsetSum(arr.Length, arr, sum / 2);
}
static void Main() {
int[] arr = { 1, 5, 11, 5 };
if (equalPartition(arr)) {
Console.WriteLine("True");
} else {
Console.WriteLine("False");
}
}
}
// JavaScript program to partition a Set
// into Two Subsets of Equal Sum
// using recursion
function isSubsetSum(n, arr, sum) {
// base cases
if (sum == 0)
return true;
if (n == 0)
return false;
// If element is greater than sum, then ignore it
if (arr[n - 1] > sum)
return isSubsetSum(n - 1, arr, sum);
// Check if sum can be obtained by any of the following
// (a) including the current element
// (b) excluding the current element
return isSubsetSum(n - 1, arr, sum) ||
isSubsetSum(n - 1, arr, sum - arr[n - 1]);
}
function equalPartition(arr) {
// Calculate sum of the elements in array
let sum = arr.reduce((a, b) => a + b, 0);
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 !== 0)
return false;
// Find if there is subset with sum equal
// to half of total sum
return isSubsetSum(arr.length, arr, sum / 2);
}
const arr = [1, 5, 11, 5];
if (equalPartition(arr)) {
console.log("True");
} else {
console.log("False");
}
Output
True
[Better Approach 1] Using Top-Down DP (Memoization) - O(sum*n) Time and O(sum*n) Space
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming.
1. Optimal Substructure:
The solution to the subset sum problem can be derived from the optimal solutions of smaller subproblems. Specifically, for any given n (the number of elements considered) and a target sum, we can express the recursive relation as follows:
- If the last element (arr[n-1]) is greater than sum, we cannot include it in our subset isSubsetSum(arr,n,sum) = isSubsetSum(arr,n-1,sum)
If the last element is less than or equal to sum, we have two choices:
- Include the last element in the subset, isSubsetSum(arr, n, sum) = isSubsetSum(arr, n-1, sum-arr[n-1])
- Exclude the last element, isSubsetSum(arr, n, sum) = isSubsetSum(arr, n-1, sum)
2. Overlapping Subproblems:
When implementing a recursive approach to solve the subset sum problem, we observe that many subproblems are computed multiple times.
- The recursive solution involves changing two parameters: the current index in the array (n) and the current target sum (sum). We need to track both parameters, so we create a 2D array of size (n+1) x (sum + 1) because the value of n will be in the range [0, n] and sum will be in the range [0, sum].
- We initialize the 2D array with -1 to indicate that no subproblems have been computed yet.
- We check if the value at memo[n][sum] is -1. If it is, we proceed to compute the result. otherwise, we return the stored result.
// C++ program to partition a Set
// into Two Subsets of Equal Sum
// using recursion
#include <bits/stdc++.h>
using namespace std;
// A utility function that returns true if there is
// a subset of arr[] with sum equal to given sum
bool isSubsetSum(int n, vector<int>& arr, int sum,
vector<vector<int>> &memo) {
// base cases
if (sum == 0)
return true;
if (n == 0)
return false;
if (memo[n-1][sum]!=-1) return memo[n-1][sum];
// If element is greater than sum, then ignore it
if (arr[n-1] > sum)
return isSubsetSum(n-1, arr, sum, memo);
// Check if sum can be obtained by any of the following
// (a) including the current element
// (b) excluding the current element
return memo[n-1][sum] =
isSubsetSum(n-1, arr, sum, memo) ||
isSubsetSum(n-1, arr, sum - arr[n-1], memo);
}
// Returns true if arr[] can be partitioned in two
// subsets of equal sum, otherwise false
bool equalPartition(vector<int>& arr) {
// Calculate sum of the elements in array
int sum = accumulate(arr.begin(), arr.end(), 0);
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
vector<vector<int>> memo(arr.size(), vector<int>(sum+1, -1));
// Find if there is subset with sum equal
// to half of total sum
return isSubsetSum(arr.size(), arr, sum / 2, memo);
}
int main() {
vector<int> arr = { 1, 5, 11, 5};
if (equalPartition(arr)) {
cout << "True" << endl;
}else{
cout << "False" << endl;
}
return 0;
}
// Java program to partition a Set
// into Two Subsets of Equal Sum
// using top down approach
import java.util.Arrays;
class GfG {
static boolean isSubsetSum(int n, int[] arr,
int sum, int[][] memo) {
// base cases
if (sum == 0)
return true;
if (n == 0)
return false;
if (memo[n - 1][sum] != -1)
return memo[n - 1][sum] == 1;
// If element is greater than sum, then ignore it
if (arr[n - 1] > sum)
return isSubsetSum(n - 1, arr, sum, memo);
// Check if sum can be obtained by any of the following
// (a) including the current element
// (b) excluding the current element
memo[n - 1][sum] = (isSubsetSum(n - 1, arr, sum, memo) ||
isSubsetSum(n - 1, arr, sum - arr[n - 1], memo)) ? 1 : 0;
return memo[n - 1][sum] == 1;
}
static boolean equalPartition(int[] arr) {
// Calculate sum of the elements in array
int sum = 0;
for (int num : arr) {
sum += num;
}
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
int[][] memo = new int[arr.length][sum + 1];
for (int[] row : memo) {
Arrays.fill(row, -1);
}
// Find if there is subset with sum equal
// to half of total sum
return isSubsetSum(arr.length, arr, sum / 2, memo);
}
public static void main(String[] args) {
int[] arr = {1, 5, 11, 5};
if (equalPartition(arr)) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
# Python program to partition a Set
# into Two Subsets of Equal Sum
# using top down approach
def isSubsetSum(n, arr, sum, memo):
# base cases
if sum == 0:
return True
if n == 0:
return False
if memo[n-1][sum] != -1:
return memo[n-1][sum]
# If element is greater than sum, then ignore it
if arr[n-1] > sum:
return isSubsetSum(n-1, arr, sum, memo)
# Check if sum can be obtained by any of the following
# (a) including the current element
# (b) excluding the current element
memo[n-1][sum] = isSubsetSum(n-1, arr, sum, memo) or\
isSubsetSum(n-1, arr, sum - arr[n-1], memo)
return memo[n-1][sum]
def equalPartition(arr):
# Calculate sum of the elements in array
arrSum = sum(arr)
# If sum is odd, there cannot be two
# subsets with equal sum
if arrSum % 2 != 0:
return False
memo = [[-1 for _ in range(arrSum+1)] for _ in range(len(arr))]
# Find if there is subset with sum equal
# to half of total sum
return isSubsetSum(len(arr), arr, arrSum // 2, memo)
if __name__ == "__main__":
arr = [1, 5, 11, 5]
if equalPartition(arr):
print("True")
else:
print("False")
// C# program to partition a Set
// into Two Subsets of Equal Sum
// using top down approach
using System;
class GfG {
static bool isSubsetSum(int n, int[] arr, int sum,
int[,] memo) {
// base cases
if (sum == 0)
return true;
if (n == 0)
return false;
if (memo[n - 1, sum] != -1)
return memo[n - 1, sum] == 1;
// If element is greater than sum, then ignore it
if (arr[n - 1] > sum)
return isSubsetSum(n - 1, arr, sum, memo);
// Check if sum can be obtained by any of the following
// (a) including the current element
// (b) excluding the current element
memo[n - 1, sum] = (isSubsetSum(n - 1, arr, sum, memo) ||
isSubsetSum(n - 1, arr, sum - arr[n - 1], memo)) ? 1 : 0;
return memo[n - 1, sum] == 1;
}
static bool equalPartition(int[] arr) {
// Calculate sum of the elements in array
int sum = 0;
foreach (int num in arr) {
sum += num;
}
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
int[,] memo = new int[arr.Length, sum + 1];
for (int i = 0; i < arr.Length; i++) {
for (int j = 0; j <= sum; j++) {
memo[i, j] = -1;
}
}
// Find if there is subset with sum equal
// to half of total sum
return isSubsetSum(arr.Length, arr, sum / 2, memo);
}
static void Main() {
int[] arr = { 1, 5, 11, 5 };
if (equalPartition(arr)) {
Console.WriteLine("True");
} else {
Console.WriteLine("False");
}
}
}
// JavaScript program to partition a Set
// into Two Subsets of Equal Sum
// using top down approach
function isSubsetSum(n, arr, sum, memo) {
// base cases
if (sum == 0)
return true;
if (n == 0)
return false;
if (memo[n - 1][sum] !== -1)
return memo[n - 1][sum];
// If element is greater than sum, then ignore it
if (arr[n - 1] > sum)
return isSubsetSum(n - 1, arr, sum, memo);
// Check if sum can be obtained by any of the following
// (a) including the current element
// (b) excluding the current element
memo[n - 1][sum] = isSubsetSum(n - 1, arr, sum, memo) ||
isSubsetSum(n - 1, arr, sum - arr[n - 1], memo);
return memo[n - 1][sum];
}
function equalPartition(arr) {
// Calculate sum of the elements in array
let sum = arr.reduce((a, b) => a + b, 0);
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 !== 0)
return false;
let memo = Array.from(Array(arr.length), () => Array(sum + 1).fill(-1));
// Find if there is subset with sum equal
// to half of total sum
return isSubsetSum(arr.length, arr, sum / 2, memo);
}
const arr = [1, 5, 11, 5];
if (equalPartition(arr)) {
console.log("True");
} else {
console.log("False");
}
Output
True
[Better Approach 2] Using Bottom-Up DP (Tabulation) - O(sum*n) Time and O(sum*n) Space
The approach is similar to the previous one. just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner.
So we will create a 2D array of size (n + 1) * (sum + 1) of type boolean. The state dp[i][j] will be true if there exists a subset of elements from arr[0 . . . i] with sum = ‘j’.
The dynamic programming relation is as follows:
if (arr[i-1]>j)
dp[i][j]=dp[i-1][j]
else
dp[i][j]=dp[i-1][j] OR dp[i-1][j-arr[i-1]]
This means that if the current element has a value greater than the ‘current sum value’ we will copy the answer for previous cases and if the current sum value is greater than the ‘ith’ element we will see if any of the previous states have already computed the sum = j OR any previous states computed a value ‘j – arr[i]’ which will solve our purpose.
// C++ program to partition a Set
// into Two Subsets of Equal Sum
// using top up approach
#include <bits/stdc++.h>
using namespace std;
// Returns true if arr[] can be partitioned in two
// subsets of equal sum, otherwise false
bool equalPartition(vector<int>& arr) {
// Calculate sum of the elements in array
int sum = accumulate(arr.begin(), arr.end(), 0);
int n = arr.size();
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
sum = sum/2;
// Create a 2D vector for storing results
// of subproblems
vector<vector<bool>> dp(n + 1, vector<bool>(sum + 1, false));
// If sum is 0, then answer is true (empty subset)
for (int i = 0; i <= n; i++)
dp[i][0] = true;
// Fill the dp table in bottom-up manner
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (j < arr[i - 1]) {
// Exclude the current element
dp[i][j] = dp[i - 1][j];
}
else {
// Include or exclude
dp[i][j] = dp[i - 1][j]
|| dp[i - 1][j - arr[i - 1]];
}
}
}
return dp[n][sum];
}
int main() {
vector<int> arr = { 1, 5, 11, 5};
if (equalPartition(arr)) {
cout << "True" << endl;
}else{
cout << "False" << endl;
}
return 0;
}
// Java program to partition a Set
// into Two Subsets of Equal Sum
// using top up approach
class GfG {
static boolean equalPartition(int[] arr) {
// Calculate sum of the elements in array
int sum = 0;
for (int num : arr) {
sum += num;
}
int n = arr.length;
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
sum = sum / 2;
// Create a 2D array for storing results
// of subproblems
boolean[][] dp = new boolean[n + 1][sum + 1];
// If sum is 0, then answer is true (empty subset)
for (int i = 0; i <= n; i++) {
dp[i][0] = true;
}
// Fill the dp table in bottom-up manner
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (j < arr[i - 1]) {
// Exclude the current element
dp[i][j] = dp[i - 1][j];
} else {
// Include or exclude
dp[i][j] = dp[i - 1][j] ||
dp[i - 1][j - arr[i - 1]];
}
}
}
return dp[n][sum];
}
public static void main(String[] args) {
int[] arr = {1, 5, 11, 5};
if (equalPartition(arr)) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
# Python program to partition a Set
# into Two Subsets of Equal Sum
# using top up approach
def equalPartition(arr):
# Calculate sum of the elements in array
arrSum = sum(arr)
n = len(arr)
# If sum is odd, there cannot be two
# subsets with equal sum
if arrSum % 2 != 0:
return False
arrSum = arrSum // 2
# Create a 2D array for storing results
# of subproblems
dp = [[False] * (arrSum + 1) for _ in range(n + 1)]
# If sum is 0, then answer is true (empty subset)
for i in range(n + 1):
dp[i][0] = True
# Fill the dp table in bottom-up manner
for i in range(1, n + 1):
for j in range(1, arrSum + 1):
if j < arr[i - 1]:
# Exclude the current element
dp[i][j] = dp[i - 1][j]
else:
# Include or exclude
dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]
return dp[n][arrSum]
if __name__ == "__main__":
arr = [1, 5, 11, 5]
if equalPartition(arr):
print("True")
else:
print("False")
// C# program to partition a Set
// into Two Subsets of Equal Sum
// using top up approach
using System;
class GfG {
static bool equalPartition(int[] arr) {
// Calculate sum of the elements in array
int sum = 0;
foreach (int num in arr) {
sum += num;
}
int n = arr.Length;
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
sum = sum / 2;
// Create a 2D array for storing results
// of subproblems
bool[,] dp = new bool[n + 1, sum + 1];
// If sum is 0, then answer is true (empty subset)
for (int i = 0; i <= n; i++) {
dp[i, 0] = true;
}
// Fill the dp table in bottom-up manner
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (j < arr[i - 1]) {
// Exclude the current element
dp[i, j] = dp[i - 1, j];
} else {
// Include or exclude
dp[i, j] = dp[i - 1, j] ||
dp[i - 1, j - arr[i - 1]];
}
}
}
return dp[n, sum];
}
static void Main() {
int[] arr = { 1, 5, 11, 5 };
if (equalPartition(arr)) {
Console.WriteLine("True");
} else {
Console.WriteLine("False");
}
}
}
// JavaScript program to partition a Set
// into Two Subsets of Equal Sum
// using top up approach
function equalPartition(arr) {
// Calculate sum of the elements in array
let sum = arr.reduce((a, b) => a + b, 0);
let n = arr.length;
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 !== 0)
return false;
sum = sum / 2;
// Create a 2D array for storing results
// of subproblems
let dp = Array.from({ length: n + 1 }, () => Array(sum + 1).fill(false));
// If sum is 0, then answer is true (empty subset)
for (let i = 0; i <= n; i++) {
dp[i][0] = true;
}
// Fill the dp table in bottom-up manner
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= sum; j++) {
if (j < arr[i - 1]) {
// Exclude the current element
dp[i][j] = dp[i - 1][j];
} else {
// Include or exclude
dp[i][j] = dp[i - 1][j] ||
dp[i - 1][j - arr[i - 1]];
}
}
}
return dp[n][sum];
}
//Driver Code
const arr = [1, 5, 11, 5];
if (equalPartition(arr)) {
console.log("True");
} else {
console.log("False");
}
Output
True
[Expected Approach] Using Space Optimized DP - O(sum*n) Time and O(sum) Space
In previous approach of dynamic programming we have derive the relation between states as given below:
if (arr[i-1]>j)
dp[i][j] = dp[i-1][j]
else
dp[i][j] = dp[i-1][j] OR dp[i-1][j-arr[i-1]]If we observe that for calculating current dp[i][j] state we only need previous row dp[i-1][j] or dp[i-1][j-arr[i-1]]. There is no need to store all the previous states just one previous state is used to compute result.
Approach:
- Define two arrays prev and curr of size sum+1 to store the just previous row result and current row result respectively.
- Once curr array is calculated then curr becomes our prev for the next row.
- When all rows are processed the answer is stored in prev array.
// C++ program to partition a Set
// into Two Subsets of Equal Sum
// using space optimised
#include <bits/stdc++.h>
using namespace std;
// Returns true if arr[] can be partitioned in two
// subsets of equal sum, otherwise false
bool equalPartition(vector<int>& arr) {
// Calculate sum of the elements in array
int sum = accumulate(arr.begin(), arr.end(), 0);
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
sum = sum / 2;
int n = arr.size();
vector<bool> prev(sum + 1, false), curr(sum + 1);
// Mark prev[0] = true as it is true
// to make sum = 0 using 0 elements
prev[0] = true;
// Fill the subset table in
// bottom up manner
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= sum; j++) {
if (j < arr[i - 1])
curr[j] = prev[j];
else
curr[j] = (prev[j] || prev[j - arr[i - 1]]);
}
prev = curr;
}
return prev[sum];
}
int main() {
vector<int> arr = { 1, 5, 11, 5};
if (equalPartition(arr)) {
cout << "True" << endl;
}else{
cout << "False" << endl;
}
return 0;
}
// Java program to partition a Set
// into Two Subsets of Equal Sum
// using space optimised
class GfG {
static boolean equalPartition(int[] arr) {
// Calculate sum of the elements in array
int sum = 0;
for (int num : arr) {
sum += num;
}
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
sum = sum / 2;
int n = arr.length;
boolean[] prev = new boolean[sum + 1];
boolean[] curr = new boolean[sum + 1];
// Mark prev[0] = true as it is true
// to make sum = 0 using 0 elements
prev[0] = true;
// Fill the subset table in
// bottom-up manner
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= sum; j++) {
if (j < arr[i - 1])
curr[j] = prev[j];
else
curr[j] = (prev[j] || prev[j - arr[i - 1]]);
}
// copy curr into prev
for (int j=0; j<=sum; j++) {
prev[j] = curr[j];
}
}
return prev[sum];
}
public static void main(String[] args) {
int[] arr = {1, 5, 11, 5};
if (equalPartition(arr)) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
# Python program to partition a Set
# into Two Subsets of Equal Sum
# using space optimised
def equalPartition(arr):
# Calculate sum of the elements in array
arrSum = sum(arr)
# If sum is odd, there cannot be two
# subsets with equal sum
if arrSum % 2 != 0:
return False
arrSum = arrSum // 2
n = len(arr)
prev = [False] * (arrSum + 1)
curr = [False] * (arrSum + 1)
# Mark prev[0] = true as it is true
# to make sum = 0 using 0 elements
prev[0] = True
# Fill the subset table in
# bottom-up manner
for i in range(1, n + 1):
for j in range(arrSum + 1):
if j < arr[i - 1]:
curr[j] = prev[j]
else:
curr[j] = (prev[j] or prev[j - arr[i - 1]])
prev = curr.copy()
return prev[arrSum]
if __name__ == "__main__":
arr = [1, 5, 11, 5]
if equalPartition(arr):
print("True")
else:
print("False")
// C# program to partition a Set
// into Two Subsets of Equal Sum
// using space optimised
using System;
class GfG {
static bool equalPartition(int[] arr) {
// Calculate sum of the elements in array
int sum = 0;
foreach (int num in arr) {
sum += num;
}
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 != 0)
return false;
sum = sum / 2;
int n = arr.Length;
bool[] prev = new bool[sum + 1];
bool[] curr = new bool[sum + 1];
// Mark prev[0] = true as it is true
// to make sum = 0 using 0 elements
prev[0] = true;
// Fill the subset table in
// bottom-up manner
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= sum; j++) {
if (j < arr[i - 1])
curr[j] = prev[j];
else
curr[j] = (prev[j] || prev[j - arr[i - 1]]);
}
prev = (bool[])curr.Clone();
}
return prev[sum];
}
static void Main() {
int[] arr = { 1, 5, 11, 5 };
if (equalPartition(arr)) {
Console.WriteLine("True");
} else {
Console.WriteLine("False");
}
}
}
// JavaScript program to partition a Set
// into Two Subsets of Equal Sum
// using space optimised
function equalPartition(arr) {
// Calculate sum of the elements in array
let sum = arr.reduce((a, b) => a + b, 0);
// If sum is odd, there cannot be two
// subsets with equal sum
if (sum % 2 !== 0)
return false;
sum = sum / 2;
let n = arr.length;
let prev = Array(sum + 1).fill(false);
let curr = Array(sum + 1).fill(false);
// Mark prev[0] = true as it is true
// to make sum = 0 using 0 elements
prev[0] = true;
// Fill the subset table in
// bottom-up manner
for (let i = 1; i <= n; i++) {
for (let j = 0; j <= sum; j++) {
if (j < arr[i - 1]) {
curr[j] = prev[j];
} else {
curr[j] = (prev[j] || prev[j - arr[i - 1]]);
}
}
prev = [...curr];
}
return prev[sum];
}
// Driver code
const arr = [1, 5, 11, 5];
if (equalPartition(arr)) {
console.log("True");
} else {
console.log("False");
}
Output
True
Related Articles: