Open In App

Print equal sum sets of array (Partition problem) | Set 1

Last Updated : 14 Sep, 2022
Comments
Improve
Suggest changes
10 Likes
Like
Report

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++
Java Python3 C# PHP JavaScript

Output
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


Next Article
Article Tags :
Practice Tags :

Similar Reads