Print equal sum sets of Array (Partition Problem) using Dynamic Programming
Last Updated :
23 Apr, 2025
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both sets is equal. If it is possible, then print both sets. If it is not possible then output -1.
Examples :
Input : arr = {5, 5, 1, 11}
Output : Set 1 = {5, 5, 1}, Set 2 = {11}
Sum of both the sets is 11 and equal.
Input : arr = {1, 5, 3}
Output : -1
No partitioning results in equal sum sets.
Prerequisite: Partition Problem
Approach:
In the previous post, a solution using recursion is discussed. In this post, a solution using Dynamic Programming is explained.
The idea is to declare two sets set 1 and set 2. To recover the solution, traverse the boolean dp table backward starting from the final result dp[n][k], where n = number of elements and k = sum/2. Set 1 will consist of elements that contribute to sum k and other elements that do not contribute are added to set 2. Follow these steps at each position to recover the solution.
- Check if dp[i-1][sum] is true or not. If it is true, then the current element does not contribute to sum k. Add this element to set 2. Update index i by i-1 and sum remains unchanged.
- If dp[i-1][sum] is false, then current element contribute to sum k. Add current element to set 1. Update index i by i-1 and sum by sum-arr[i-1].
Repeat the above steps until each index position is traversed.
Implementation:
C++
// CPP program to print equal sum sets of array.
#include <bits/stdc++.h>
using namespace std;
// Function to print equal sum
// sets of array.
void printEqualSumSets(int arr[], int n)
{
int i, currSum;
// Finding sum of array elements
int sum = accumulate(arr, arr+n, 0);
// Check sum is even or odd. If odd
// then array cannot be partitioned.
// Print -1 and return.
if (sum & 1) {
cout << "-1";
return;
}
// Divide sum by 2 to find
// sum of two possible subsets.
int k = sum >> 1;
// Boolean DP table to store result
// of states.
// dp[i][j] = true if there is a
// subset of elements in first i elements
// of array that has sum equal to j.
bool dp[n + 1][k + 1];
// If number of elements are zero, then
// no sum can be obtained.
for (i = 1; i <= k; i++)
dp[0][i] = false;
// Sum 0 can be obtained by not selecting
// any element.
for (i = 0; i <= n; i++)
dp[i][0] = true;
// Fill the DP table in bottom up manner.
for (i = 1; i <= n; i++) {
for (currSum = 1; currSum <= k; currSum++) {
// Excluding current element.
dp[i][currSum] = dp[i - 1][currSum];
// Including current element
if (arr[i - 1] <= currSum)
dp[i][currSum] = dp[i][currSum] |
dp[i - 1][currSum - arr[i - 1]];
}
}
// Required sets set1 and set2.
vector<int> set1, set2;
// If partition is not possible print
// -1 and return.
if (!dp[n][k]) {
cout << "-1\n";
return;
}
// Start from last element in dp table.
i = n;
currSum = k;
while (i > 0 && currSum >= 0) {
// If current element does not
// contribute to k, then it belongs
// to set 2.
if (dp[i - 1][currSum]) {
i--;
set2.push_back(arr[i]);
}
// If current element contribute
// to k then it belongs to set 1.
else if (dp[i - 1][currSum - arr[i - 1]]) {
i--;
currSum -= arr[i];
set1.push_back(arr[i]);
}
}
// Print elements of both the sets.
cout << "Set 1 elements: ";
for (i = 0; i < set1.size(); i++)
cout << set1[i] << " ";
cout << "\nSet 2 elements: ";
for (i = 0; i < set2.size(); i++)
cout << set2[i] << " ";
}
// Driver program.
int main()
{
int arr[] = { 5, 5, 1, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
printEqualSumSets(arr, n);
return 0;
}
Java
// Java program to print
// equal sum sets of array.
import java.io.*;
import java.util.*;
class GFG
{
// Function to print equal
// sum sets of array.
static void printEqualSumSets(int []arr,
int n)
{
int i, currSum, sum = 0;
// Finding sum of array elements
for (i = 0; i < arr.length; i++)
sum += arr[i];
// Check sum is even or odd.
// If odd then array cannot
// be partitioned. Print -1
// and return.
if ((sum & 1) == 1)
{
System.out.print("-1");
return;
}
// Divide sum by 2 to find
// sum of two possible subsets.
int k = sum >> 1;
// Boolean DP table to store
// result of states.
// dp[i,j] = true if there is a
// subset of elements in first i
// elements of array that has sum
// equal to j.
boolean [][]dp = new boolean[n + 1][k + 1];
// If number of elements are zero,
// then no sum can be obtained.
for (i = 1; i <= k; i++)
dp[0][i] = false;
// Sum 0 can be obtained by
// not selecting any element.
for (i = 0; i <= n; i++)
dp[i][0] = true;
// Fill the DP table
// in bottom up manner.
for (i = 1; i <= n; i++)
{
for (currSum = 1;
currSum <= k;
currSum++)
{
// Excluding current element.
dp[i][currSum] = dp[i - 1][currSum];
// Including current element
if (arr[i - 1] <= currSum)
dp[i][currSum] = dp[i][currSum] |
dp[i - 1][currSum - arr[i - 1]];
}
}
// Required sets set1 and set2.
List<Integer> set1 = new ArrayList<Integer>();
List<Integer> set2 = new ArrayList<Integer>();
// If partition is not possible
// print -1 and return.
if (!dp[n][k])
{
System.out.print("-1\n");
return;
}
// Start from last
// element in dp table.
i = n;
currSum = k;
while (i > 0 && currSum >= 0)
{
// If current element does
// not contribute to k, then
// it belongs to set 2.
if (dp[i - 1][currSum])
{
i--;
set2.add(arr[i]);
}
// If current element contribute
// to k then it belongs to set 1.
else if (dp[i - 1][currSum - arr[i - 1]])
{
i--;
currSum -= arr[i];
set1.add(arr[i]);
}
}
// Print elements of both the sets.
System.out.print("Set 1 elements: ");
for (i = 0; i < set1.size(); i++)
System.out.print(set1.get(i) + " ");
System.out.print("\nSet 2 elements: ");
for (i = 0; i < set2.size(); i++)
System.out.print(set2.get(i) + " ");
}
// Driver Code
public static void main(String args[])
{
int []arr = new int[]{ 5, 5, 1, 11 };
int n = arr.length;
printEqualSumSets(arr, n);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Python3
# Python3 program to print equal sum
# sets of array.
import numpy as np
# Function to print equal sum
# sets of array.
def printEqualSumSets(arr, n) :
# Finding sum of array elements
sum_array = sum(arr)
# Check sum is even or odd. If odd
# then array cannot be partitioned.
# Print -1 and return.
if (sum_array & 1) :
print("-1")
return
# Divide sum by 2 to find
# sum of two possible subsets.
k = sum_array >> 1
# Boolean DP table to store result
# of states.
# dp[i][j] = true if there is a
# subset of elements in first i elements
# of array that has sum equal to j.
dp = np.zeros((n + 1, k + 1))
# If number of elements are zero, then
# no sum can be obtained.
for i in range(1, k + 1) :
dp[0][i] = False
# Sum 0 can be obtained by not
# selecting any element.
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 currSum in range(1, k + 1) :
# Excluding current element.
dp[i][currSum] = dp[i - 1][currSum]
# Including current element
if (arr[i - 1] <= currSum) :
dp[i][currSum] = (dp[i][currSum] or
dp[i - 1][currSum - arr[i - 1]])
# Required sets set1 and set2.
set1, set2 = [], []
# If partition is not possible print
# -1 and return.
if ( not dp[n][k]) :
print("-1")
return
# Start from last element in dp table.
i = n
currSum = k
while (i > 0 and currSum >= 0) :
# If current element does not
# contribute to k, then it belongs
# to set 2.
if (dp[i - 1][currSum]) :
i -= 1
set2.append(arr[i])
# If current element contribute
# to k then it belongs to set 1.
elif (dp[i - 1][currSum - arr[i - 1]]) :
i -= 1
currSum -= arr[i]
set1.append(arr[i])
# Print elements of both the sets.
print("Set 1 elements:", end = " ")
for i in range(len(set1)) :
print(set1[i], end = " ")
print("\nSet 2 elements:", end = " ")
for i in range(len(set2)) :
print(set2[i], end = " ")
# Driver Code
if __name__ == "__main__" :
arr = [ 5, 5, 1, 11 ]
n = len(arr)
printEqualSumSets(arr, n)
# This code is contributed by Ryuga
C#
// C# program to print
// equal sum sets of array.
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
// Function to print equal
// sum sets of array.
static void printEqualSumSets(int []arr,
int n)
{
int i, currSum, sum = 0;
// Finding sum of array elements
for (i = 0; i < arr.Length; i++)
sum += arr[i];
// Check sum is even or odd.
// If odd then array cannot
// be partitioned. Print -1
// and return.
if ((sum & 1) == 1)
{
Console.Write("-1");
return;
}
// Divide sum by 2 to find
// sum of two possible subsets.
int k = sum >> 1;
// Boolean DP table to store
// result of states.
// dp[i,j] = true if there is a
// subset of elements in first i
// elements of array that has sum
// equal to j.
bool [,]dp = new bool[n + 1, k + 1];
// If number of elements are zero,
// then no sum can be obtained.
for (i = 1; i <= k; i++)
dp[0, i] = false;
// Sum 0 can be obtained by
// not selecting any element.
for (i = 0; i <= n; i++)
dp[i, 0] = true;
// Fill the DP table
// in bottom up manner.
for (i = 1; i <= n; i++)
{
for (currSum = 1; currSum <= k; currSum++)
{
// Excluding current element.
dp[i, currSum] = dp[i - 1, currSum];
// Including current element
if (arr[i - 1] <= currSum)
dp[i, currSum] = dp[i, currSum] |
dp[i - 1, currSum - arr[i - 1]];
}
}
// Required sets set1 and set2.
List<int> set1 = new List<int>();
List<int> set2 = new List<int>();
// If partition is not possible
// print -1 and return.
if (!dp[n, k])
{
Console.Write("-1\n");
return;
}
// Start from last
// element in dp table.
i = n;
currSum = k;
while (i > 0 && currSum >= 0)
{
// If current element does
// not contribute to k, then
// it belongs to set 2.
if (dp[i - 1, currSum])
{
i--;
set2.Add(arr[i]);
}
// If current element contribute
// to k then it belongs to set 1.
else if (dp[i - 1, currSum - arr[i - 1]])
{
i--;
currSum -= arr[i];
set1.Add(arr[i]);
}
}
// Print elements of both the sets.
Console.Write("Set 1 elements: ");
for (i = 0; i < set1.Count; i++)
Console.Write(set1[i] + " ");
Console.Write("\nSet 2 elements: ");
for (i = 0; i < set2.Count; i++)
Console.Write(set2[i] + " ");
}
// Driver Code.
static void Main()
{
int []arr = { 5, 5, 1, 11 };
int n = arr.Length;
printEqualSumSets(arr, n);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
JavaScript
<script>
// Javascript program to print equal sum sets of array.
// Function to print equal sum
// sets of array.
function printEqualSumSets(arr, n)
{
var i, currSum;
// Finding sum of array elements
var sum = 0;
for(var i =0; i< arr.length; i++)
{
sum+=arr[i];
}
// Check sum is even or odd. If odd
// then array cannot be partitioned.
// Print -1 and return.
if (sum & 1) {
document.write( "-1");
return;
}
// Divide sum by 2 to find
// sum of two possible subsets.
var k = sum >> 1;
// Boolean DP table to store result
// of states.
// dp[i][j] = true if there is a
// subset of elements in first i elements
// of array that has sum equal to j.
var dp = Array.from(Array(n+1), ()=> Array(k+1));
// If number of elements are zero, then
// no sum can be obtained.
for (i = 1; i <= k; i++)
dp[0][i] = false;
// Sum 0 can be obtained by not selecting
// any element.
for (i = 0; i <= n; i++)
dp[i][0] = true;
// Fill the DP table in bottom up manner.
for (i = 1; i <= n; i++) {
for (currSum = 1; currSum <= k; currSum++) {
// Excluding current element.
dp[i][currSum] = dp[i - 1][currSum];
// Including current element
if (arr[i - 1] <= currSum)
dp[i][currSum] = dp[i][currSum] |
dp[i - 1][currSum - arr[i - 1]];
}
}
// Required sets set1 and set2.
var set1 = [], set2=[];
// If partition is not possible print
// -1 and return.
if (!dp[n][k]) {
document.write( "-1<br>");
return;
}
// Start from last element in dp table.
i = n;
currSum = k;
while (i > 0 && currSum >= 0) {
// If current element does not
// contribute to k, then it belongs
// to set 2.
if (dp[i - 1][currSum]) {
i--;
set2.push(arr[i]);
}
// If current element contribute
// to k then it belongs to set 1.
else if (dp[i - 1][currSum - arr[i - 1]]) {
i--;
currSum -= arr[i];
set1.push(arr[i]);
}
}
// Print elements of both the sets.
document.write( "Set 1 elements: ");
for (i = 0; i < set1.length; i++)
document.write( set1[i] + " ");
document.write( "<br>Set 2 elements: ");
for (i = 0; i < set2.length; i++)
document.write( set2[i] + " ");
}
// Driver program.
var arr = [ 5, 5, 1, 11 ];
var n = arr.length;
printEqualSumSets(arr, n);
</script>
OutputSet 1 elements: 1 5 5
Set 2 elements: 11
Complexity Analysis:
- Time Complexity: O(n*k), where k = sum(arr) / 2
- Auxiliary Space: O(n*k)
Similar Reads
Print equal sum sets of array (Partition problem) | Set 1 Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both the sets is equal. If it is possible, then print both the sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2
14 min read
Partition of a set into k subsets with equal sum using BitMask and DP Given an integer array arr[] and an integer k, the task is to check if it is possible to divide the given array into k non-empty subsets of equal sum such that every array element is part of a single subset.Examples: Input: arr[] = [2, 1, 4, 5, 6], k = 3 Output: trueExplanation: Possible subsets of
9 min read
Sum over Subsets | Dynamic Programming Prerequisite: Basic Dynamic Programming, Bitmasks Consider the following problem where we will use Sum over subset Dynamic Programming to solve it. Given an array of 2n integers, we need to calculate function F(x) = ?Ai such that x&i==i for all x. i.e, i is a bitwise subset of x. i will be a bit
10 min read
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: Th
15+ min read
Partition of a set into K subsets with equal sum Given an integer array arr[] and an integer k, the task is to check if it is possible to divide the given array into k non-empty subsets of equal sum such that every array element is part of a single subset.Examples: Input: arr[] = [2, 1, 4, 5, 6], k = 3 Output: trueExplanation: Possible subsets of
9 min read
Check if it possible to partition in k subarrays with equal sum Given an array A of size N, and a number K. Task is to find out if it is possible to partition the array A into K contiguous subarrays such that the sum of elements within each of these subarrays is the same. Prerequisite: Count the number of ways to divide an array into three contiguous parts havin
15+ min read
Minimum Subset sum difference problem with Subset partitioning Given a set of N integers with up to 40 elements, the task is to partition the set into two subsets of equal size (or the closest possible), such that the difference between the sums of the subsets is minimized. If the size of the set is odd, one subset will have one more element than the other. If
13 min read
Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum Given an array A containing N elements. Partition any subset of this array into two disjoint subsets such that both the subsets have an identical sum. Obtain the maximum sum that can be obtained after partitioning. Note: It is not necessary to partition the entire array, that is any element might no
15+ min read
Subset sum problem where Array sum is at most N Given an array arr[] of size N such that the sum of all the array elements does not exceed N, and array queries[] containing Q queries. For each query, the task is to find if there is a subset of the array whose sum is the same as queries[i]. Examples: Input: arr[] = {1, 0, 0, 0, 0, 2, 3}, queries[]
10 min read
Check if an array can be split into 3 subsequences of equal sum or not Given an array arr[] having N integers. The task is to determine if the array can be partitioned into 3 subsequences of an equal sum or not. If yes then print âYesâ. Otherwise, print âNoâ. Examples: Input: arr[] = {1, 1, 1}Output: YesExplanation:Here array can be partition into 3 equal sum. {1} Inpu
15+ min read