Partition a Set into Two Subsets of Equal Sum
Last Updated :
23 Jul, 2025
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.
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++
// 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
// 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
# 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#
// 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
// 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");
}
[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++
// 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
// 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
# 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#
// 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
// 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");
}
[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++
// 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
// 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
# 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#
// 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
// 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");
}
[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++
// 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
// 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
# 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#
// 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
// 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");
}
Related Articles:
Partition a Set into Two Subsets of Equal Sum.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem