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 = {11}
Sum of both the sets is 11 and equal.
Input : arr = {1, 5, 3}
Output : -1
No partitioning results in equal sum sets.
We have already discussed a solution in Partition Problem to find if array can be partitioned or not. In this post, we print two sets that are also printed. We post pass two vectors set1 and set2 and two sum variables sum1 and sum2. Traverse the array recursively.
At every array position there are two choices: either add the current element to set 1 or to set 2. Recursively call for both the conditions and update the vectors set1 and set2 accordingly. If the current element is added to set 1 then add the current element to sum1 and insert it in vector set 1. Repeat the same if the current element is included in set 2. At the end of array traversal compare both the sums. If both the sums are equal then print both the vectors otherwise backtrack to check other possibilities.
Implementation:
C++
| // CPP program to print equal sum two subsets of// an array if it can be partitioned into subsets.#include <bits/stdc++.h>usingnamespacestd;/// Function to print the equal sum sets of the array.voidprintSets(vector<int> set1, vector<int> set2){    inti;    /// Print set 1.    for(i = 0; i < set1.size(); i++) {        cout << set1[i] << " ";    }    cout << "\n";    /// Print set 2.    for(i = 0; i < set2.size(); i++) {        cout << set2[i] << " ";    }}/// Utility function to find the sets of the array which/// have equal sum.boolfindSets(intarr[], intn, vector<int>& set1,              vector<int>& set2, intsum1, intsum2,              intpos){    /// If entire array is traversed, compare both the sums.    if(pos == n) {        /// If sums are equal print both sets and return        /// true to show sets are found.        if(sum1 == sum2) {            printSets(set1, set2);            returntrue;        }        /// If sums are not equal then return sets are not        /// found.        else            returnfalse;    }    /// Add current element to set 1.    set1.push_back(arr[pos]);    /// Recursive call after adding current element to    /// set 1.    boolres = findSets(arr, n, set1, set2, sum1 + arr[pos],                        sum2, pos + 1);    /// If this inclusion results in equal sum sets    /// partition then return true to show desired sets are    /// found.    if(res)        returnres;    /// If not then backtrack by removing current element    /// from set1 and include it in set 2.    set1.pop_back();    set2.push_back(arr[pos]);    /// Recursive call after including current element to    /// set 2.    res = findSets(arr, n, set1, set2, sum1,                   sum2 + arr[pos], pos + 1);    if(res == false)        set2.pop_back();    returnres;}/// Return true if array arr can be partitioned/// into two equal sum sets or not.boolisPartitionPoss(intarr[], intn){    /// Calculate sum of elements in array.    intsum = 0;    for(inti = 0; i < n; i++)        sum += arr[i];    /// If sum is odd then array cannot be    /// partitioned.    if(sum % 2 != 0)        returnfalse;    /// Declare vectors to store both the sets.    vector<int> set1, set2;    /// Find both the sets.    returnfindSets(arr, n, set1, set2, 0, 0, 0);}// Driver codeintmain(){    intarr[] = { 5, 5, 1, 11 };    intn = sizeof(arr) / sizeof(arr[0]);    if(!isPartitionPoss(arr, n)) {        cout << "-1";    }    return0;} | 
Java
| // Java program to print equal sum two subsets// of an array if it can be partitioned into// subsets.importjava.io.*;importjava.util.*;publicclassGFG {    // Declare Lists to store both    // the sets.    staticList<Integer> set1 = newArrayList<Integer>();    staticList<Integer> set2 = newArrayList<Integer>();    /// Function to print the equal sum sets    // of the array.    staticvoidprintSets()    {        inti;        /// Print set 1.        for(i = 0; i < set1.size(); i++) {            System.out.print(set1.get(i) + " ");        }        System.out.println();        /// Print set 2.        for(i = 0; i < set2.size(); i++) {            System.out.print(set2.get(i) + " ");        }    }    // Utility function to find the sets    // of the array which have equal sum.    staticbooleanfindSets(Integer[] arr, intn,                            intsum1, intsum2,                            intpos)    {        // If entire array is traversed,        // compare both the sums.        if(pos == n) {            // If sums are equal print            // both sets and return true            // to show sets are found.            if(sum1 == sum2) {                printSets();                returntrue;            }            // If sums are not equal            // then return sets are not            // found.            else                returnfalse;        }        // Add current element to set 1.        set1.add(arr[pos]);        // Recursive call after adding        // current element to set 1.        booleanres = findSets(arr, n, sum1 + arr[pos],                               sum2, pos + 1);        // If this inclusion results in        // equal sum sets partition then        // return true to show desired        // sets are found.        if(res == true)            returnres;        // If not then backtrack by removing        // current element from set1 and        // include it in set 2.        set1.remove(set1.size() - 1);        set2.add(arr[pos]);        // Recursive call after including        // current element to set 2.        res = findSets(arr, n, sum1, sum2                                         + arr[pos],                       pos + 1);        if(res == false)            set2.remove(set2.size() - 1);        returnres;    }    // Return true if array arr can be    // partitioned into two equal sum    // sets or not.    staticbooleanisPartitionPoss(Integer[] arr,                                   intn)    {        // Calculate sum of elements in        // array.        intsum = 0;        for(inti = 0; i < n; i++)            sum += arr[i];        // If sum is odd then array cannot        // be partitioned.        if(sum % 2!= 0)            returnfalse;        /// Find both the sets.        returnfindSets(arr, n, 0, 0, 0);    }    // Driver code    publicstaticvoidmain(String args[])    {        Integer[] arr = { 5, 5, 1, 11};        intn = arr.length;        if(isPartitionPoss(arr, n) == false) {            System.out.print("-1");        }    }}// This code is contributed by Manish Shaw// (manishshaw1) | 
Python3
| # Python3 program to print equal sum two subsets of# an array if it can be partitioned into subsets.# Function to print the equal sum sets of the array.defprintSets(set1, set2) :    # Print set 1.    fori inrange(0, len(set1)) :        print("{} ".format(set1[i]), end ="");     print("")    # Print set 2.    fori inrange(0, len(set2)) :        print("{} ".format(set2[i]), end ="");     print("")# Utility function to find the sets of the # array which have equal sum.deffindSets(arr, n, set1, set2, sum1, sum2, pos) :    # If entire array is traversed, compare both     # the sums.    if(pos ==n) :                 # If sums are equal print both sets and        # return true to show sets are found.        if(sum1 ==sum2) :            printSets(set1, set2)            returnTrue        # If sums are not equal then return         # sets are not found.        else:            returnFalse    # Add current element to set 1.    set1.append(arr[pos])    # Recursive call after adding current    # element to set 1.    res =findSets(arr, n, set1, set2,                sum1 +arr[pos], sum2, pos +1)    # If this inclusion results in an equal sum    # sets partition then return true to show     # desired sets are found.    if(res) :        returnres    # If not then backtrack by removing current    # element from set1 and include it in set 2.    set1.pop()    set2.append(arr[pos])    # Recursive call after including current     # element to set 2 and removing the element    # from set 2 if it returns False    res=findSets(arr, n, set1, set2, sum1,                      sum2 +arr[pos], pos +1)    ifnotres:                set2.pop()    returnres# Return true if array arr can be partitioned# into two equal sum sets or not.defisPartitionPoss(arr, n) :    # Calculate sum of elements in array.    sum=0    fori inrange(0, n):        sum+=arr[i]    # If sum is odd then array cannot be    # partitioned.    if(sum%2!=0) :        returnFalse    # Declare vectors to store both the sets.    set1 =[]    set2 =[]    # Find both the sets.    returnfindSets(arr, n, set1, set2, 0, 0, 0)# Driver codearr =[5, 5, 1, 11]n =len(arr)if(isPartitionPoss(arr, n) ==False) :    print("-1")    # This code is contributed by Manish Shaw# (manishshaw1) | 
C#
| // C# program to print equal sum two subsets// of an array if it can be partitioned into// subsets.usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Collections;classGFG {    /// Function to print the equal sum sets    // of the array.    staticvoidprintSets(List<int> set1,                          List<int> set2)    {        inti;        /// Print set 1.        for(i = 0; i < set1.Count; i++) {            Console.Write(set1[i] + " ");        }        Console.WriteLine();        /// Print set 2.        for(i = 0; i < set2.Count; i++) {            Console.Write(set2[i] + " ");        }    }    // Utility function to find the sets    // of the array which have equal sum.    staticboolfindSets(int[] arr, intn,                         refList<int> set1,                         refList<int> set2,                         intsum1, intsum2,                         intpos)    {        // If entire array is traversed,        // compare both the sums.        if(pos == n) {            // If sums are equal print            // both sets and return true            // to show sets are found.            if(sum1 == sum2) {                printSets(set1, set2);                returntrue;            }            // If sums are not equal            // then return sets are not            // found.            else                returnfalse;        }        // Add current element to set 1.        set1.Add(arr[pos]);        // Recursive call after adding        // current element to set 1.        boolres = findSets(arr, n, refset1,                            refset2, sum1 + arr[pos],                            sum2, pos + 1);        // If this inclusion results in        // equal sum sets partition then        // return true to show desired        // sets are found.        if(res == true)            returnres;        // If not then backtrack by removing        // current element from set1 and        // include it in set 2.        set1.RemoveAt(set1.Count - 1);        set2.Add(arr[pos]);        // Recursive call after including        // current element to set 2.        res = findSets(arr, n, refset1,                       refset2, sum1, sum2                                           + arr[pos],                       pos + 1);        if(res == false)            set2.RemoveAt(set2.Count - 1);        returnres;    }    // Return true if array arr can be    // partitioned into two equal sum    // sets or not.    staticboolisPartitionPoss(int[] arr,                                intn)    {        // Calculate sum of elements in        // array.        intsum = 0;        for(inti = 0; i < n; i++)            sum += arr[i];        // If sum is odd then array cannot        // be partitioned.        if(sum % 2 != 0)            returnfalse;        // Declare Lists to store both        // the sets.        List<int> set1 = newList<int>();        List<int> set2 = newList<int>();        /// Find both the sets.        returnfindSets(arr, n, refset1,                        refset2, 0, 0, 0);    }    // Driver code    publicstaticvoidMain()    {        int[] arr = { 5, 5, 1, 11 };        intn = arr.Length;        if(isPartitionPoss(arr, n) == false) {            Console.Write("-1");        }    }}// This code is contributed by Manish Shaw// (manishshaw1) | 
PHP
| <?php// PHP program to print equal sum // two subsets of an array if it // can be partitioned into subsets.// Function to print the equal // sum sets of the array.functionprintSets($set1, $set2){    $i= 0;        // Print set 1.    for($i= 0; $i< count($set1); $i++)     {        echo($set1[$i]." ");    }    echo("\n");    // Print set 2.    for($i= 0; $i< count($set2); $i++)     {        echo($set2[$i]." ");    }}// Utility function to find the // sets of the array which have// equal sum.functionfindSets($arr, $n, &$set1,                      &$set2, $sum1,                      $sum2, $pos){    // If entire array is traversed,    // compare both the sums.    if($pos== $n)     {        // If sums are equal print        // both sets and return         // true to show sets are found.        if($sum1== $sum2)         {            printSets($set1, $set2);            returntrue;        }        // If sums are not equal then         // return sets are not found.        else            returnfalse;         }    // Add current element to set 1.    array_push($set1, $arr[$pos]);    // Recursive call after adding     // current element to set 1.    $res= findSets($arr, $n, $set1, $set2,                     $sum1+ $arr[$pos],                     $sum2, $pos+ 1);    // If this inclusion results in    // equal sum sets partition then      // return true to show desired     // sets are found.    if($res)        return$res;    // If not then backtrack by     // removing current element     // from set1 and include it     // in set 2.    array_pop($set1);    array_push($set2, $arr[$pos]);    // Recursive call after including    // current element to set 2.    $res= findSets($arr, $n, $set1, $set2,                    $sum1, $sum2+ $arr[$pos],                                    $pos+ 1);    if($res== false){        array_pop($set2);    }    return$res;}// Return true if array arr // can be partitioned into// two equal sum sets or not.functionisPartitionPoss($arr, $n){    // Calculate sum of     // elements in array.    $sum= 0;    for($i= 0; $i< $n; $i++)         $sum+= $arr[$i];     // If sum is odd then array     // cannot be partitioned.    if($sum% 2 != 0)         returnfalse;     // Declare vectors to    // store both the sets.    $set1= array();    $set2= array();    // Find both the sets.    returnfindSets($arr, $n, $set1,                    $set2, 0, 0, 0);}// Driver code$arr= array( 5, 5, 1, 11 );$n= count($arr);if(isPartitionPoss($arr, $n) == false)    echo("-1");// This code is contributed by // Manish Shaw (manishshaw1)?> | 
Javascript
| <script>// Javascript program to print equal sum two// subsets of an array if it can be partitioned // into subsets.// Function to print the equal sum// sets of the array.functionprintSets(set1, set2){    vari;    // Print set 1.    for(i = 0; i < set1.length; i++)    {        document.write( set1[i] + " ");    }    document.write("<br>");    // Print set 2.    for(i = 0; i < set2.length; i++)    {        document.write( set2[i] + " ");    }}// Utility function to find the sets of the // array which have equal sum.functionfindSets(arr, n, set1, set2,                   sum1, sum2, pos){    // If entire array is traversed,     // compare both the sums.    if(pos == n)     {                // If sums are equal print both sets        // and return true to show sets are found.        if(sum1 == sum2)         {            printSets(set1, set2);            returntrue;        }        // If sums are not equal then        // return sets are not found.        else            returnfalse;    }    // Add current element to set 1.    set1.push(arr[pos]);    // Recursive call after adding current    // element to set 1.    varres = findSets(arr, n, set1, set2,                        sum1 + arr[pos],                       sum2, pos + 1);    // If this inclusion results in equal sum    // sets partition then return true to show    // desired sets are found.    if(res)        returnres;    // If not then backtrack by removing     // current element from set1 and     // include it in set 2.    set1.pop();    set2.push(arr[pos]);    // Recursive call after including     // current element to set 2.    res = findSets(arr, n, set1, set2,                    sum1, sum2 + arr[pos],                          pos + 1);    if(res == false)        set2.pop();    returnres;}// Return true if array arr can be partitioned// into two equal sum sets or not.functionisPartitionPoss(arr, n){    // Calculate sum of elements in array.    varsum = 0;    for(vari = 0; i < n; i++)        sum += arr[i];    // If sum is odd then array cannot be    // partitioned.    if(sum % 2 != 0)        returnfalse;    // Declare vectors to store both the sets.    varset1 = [];    varset2 = [];    // Find both the sets.    returnfindSets(arr, n, set1, set2, 0, 0, 0);}// Driver codevararr = [ 5, 5, 1, 11 ];varn = arr.length;if(!isPartitionPoss(arr, n)) {    document.write( "-1");}// This code is contributed by SoumikMondal</script> | 
5 5 1 11
Complexity Analysis:
- Time Complexity: Exponential O(2^n)
- Auxiliary Space: O(n) (Without considering size of function call stack)
Print equal sum sets of array (Partition Problem) | Set 2
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







