Find all combinations of two equal sum subsequences

Given an array arr[] of integers, the task is to find all possible ways the array could be split into two subsequences such that the sum of the elements in both the subsequences is equal. Each number in the array must belong to only one of the two subsequences. Print all possible combinations of two subsequences.
Examples:Â
Input: arr[] = {1, 2, 3, 9, 4, 5}Â
Output:Â
1 2 9 and 3 4 5Â
1 2 4 5 and 3 9Â
3 9 and 1 2 4 5Â
3 4 5 and 1 2 9Input: arr[] = {4, -1, 2, -1}Â
Output:Â
4 -1 -1 and 2Â
2 and 4 -1 -1Â
Â
Approach: A simple solution is to form all possible pairs of subsequences using recursion and compare the sum of elements in both the subsequences. For each array element, we have two choices, we can either take the current element in the first subsequence or the second.
Below is the implementation of the above approach:Â Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
#define MAX 100000Â
// Function to print the subsequence elementsvoid print(int g1[], int a, int g2[], int b){Â
    // Prints elements of the 1st subarray    for (int i = 0; i < a; i++) {        cout << g1[i] << " ";    }    cout << "and ";Â
    // Prints elements of the 2nd subarray    for (int i = 0; i < b; i++) {        cout << g2[i] << " ";    }    cout << endl;}Â
// Function that returns true if the sum of the// elements of arrays g1[] and g2[] is equalbool checksum(int g1[], int a, int g2[], int b){Â Â Â Â int i, x;Â
    // Adding elements of the 1st array    for (i = 0, x = 0; i < a; i++) {        x += g1[i];    }Â
    // Subtracting elements of the 2nd array    for (i = 0; i < b; i++) {        x -= g2[i];    }Â
    // If x is 0 then the sum of elements    // in both the arrays is equal    return (x == 0);}Â
// Function to find all valid subsequencesvoid formgroups(int arr[], int x, int g1[], int a,                int g2[], int b, int n){    // Base Case    if (x == n) {Â
        // If sum of the two subsequences        // is equal then print the elements        if (checksum(g1, a, g2, b)) {Â
            // Print the subsequences            print(g1, a, g2, b);        }        return;    }Â
    // Recursive CaseÂ
    // Choose current element to be a    // part of the first subsequence    g1[a] = arr[x];    formgroups(arr, x + 1, g1, a + 1, g2, b, n);Â
    // Choose current element to be a    // part of the second subsequence    g2[b] = arr[x];    formgroups(arr, x + 1, g1, a, g2, b + 1, n);}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 1, 2, 3, 9, 4, 5 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â
    int g1[MAX], g2[MAX];    formgroups(arr, 0, g1, 0, g2, 0, n);Â
    return 0;} |
Java
// Java implementation of the approachimport java.util.*;Â
class GFG {static int MAX = 100000;Â
// Function to print the // subsequence elementsstatic void print(int g1[], int a, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int g2[], int b){Â
    // Prints elements of the 1st subarray    for (int i = 0; i < a; i++)    {        System.out.print(g1[i] + " ");    }    System.out.print("and ");Â
    // Prints elements of the 2nd subarray    for (int i = 0; i < b; i++)     {        System.out.print(g2[i] + " ");    }    System.out.println();}Â
// Function that returns true if // the sum of the elements of // arrays g1[] and g2[] is equalstatic boolean checksum(int g1[], int a, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int g2[], int b){Â Â Â Â int i, x;Â
    // Adding elements of the 1st array    for (i = 0, x = 0; i < a; i++)     {        x += g1[i];    }Â
    // Subtracting elements of     // the 2nd array    for (i = 0; i < b; i++)    {        x -= g2[i];    }Â
    // If x is 0 then the sum of elements    // in both the arrays is equal    return (x == 0);}Â
// Function to find all valid subsequencesstatic void formgroups(int arr[], int x,                        int g1[], int a,                        int g2[], int b, int n){    // Base Case    if (x == n)     {Â
        // If sum of the two subsequences        // is equal then print the elements        if (checksum(g1, a, g2, b))         {Â
            // Print the subsequences            print(g1, a, g2, b);        }        return;    }Â
    // Recursive CaseÂ
    // Choose current element to be a    // part of the first subsequence    g1[a] = arr[x];    formgroups(arr, x + 1, g1,                     a + 1, g2, b, n);Â
    // Choose current element to be a    // part of the second subsequence    g2[b] = arr[x];    formgroups(arr, x + 1, g1, a,                 g2, b + 1, n);}Â
// Driver codepublic static void main(String[] args) {Â Â Â Â int arr[] = { 1, 2, 3, 9, 4, 5 };Â Â Â Â int n = arr.length;Â
    int []g1 = new int[MAX];    int []g2 = new int[MAX];    formgroups(arr, 0, g1, 0, g2, 0, n);}}Â
// This code is contributed by PrinciRaj1992 |
Python3
# Python 3 implementation of the approachMAX = 100000Â
# Function to print the subsequence elementsdef prints(g1, a, g2, b):         # Prints elements of the 1st subarray    for i in range(a):        print(g1[i], end = " ")         print("and ", end = "")Â
    # Prints elements of the 2nd subarray    for i in range(b):        print(g2[i], end = " ")         print("\n", end = "")Â
# Function that returns true if the sum of the# elements of arrays g1[] and g2[] is equaldef checksum(g1, a, g2, b):         # Adding elements of the 1st array    x = 0    for i in range(0, a, 1):        x += g1[i]Â
    # Subtracting elements of the 2nd array    for i in range(b):        x -= g2[i]Â
    # If x is 0 then the sum of elements    # in both the arrays is equal    return (x == 0)Â
# Function to find all valid subsequencesdef formgroups(arr, x, g1, a, g2, b, n):         # Base Case    if (x == n):                 # If sum of the two subsequences        # is equal then print the elements        if (checksum(g1, a, g2, b)):                         # Print the subsequences            prints(g1, a, g2, b)Â
        returnÂ
    # Recursive CaseÂ
    # Choose current element to be a    # part of the first subsequence    g1[a] = arr[x]    formgroups(arr, x + 1, g1, a + 1, g2, b, n)Â
    # Choose current element to be a    # part of the second subsequence    g2[b] = arr[x]    formgroups(arr, x + 1, g1, a, g2, b + 1, n)Â
# Driver codeif __name__ == '__main__':Â Â Â Â arr = [1, 2, 3, 9, 4, 5]Â Â Â Â n = len(arr)Â Â Â Â g1 = [0 for i in range(MAX)]Â Â Â Â g2 = [0 for i in range(MAX)]Â Â Â Â formgroups(arr, 0, g1, 0, g2, 0, n)Â
# This code is contributed by# Surendra_Gangwar |
C#
// C# implementation of the approachusing System;Â
class GFG {static int MAX = 100000;Â
// Function to print the // subsequence elementsstatic void print(int []g1, int a, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int []g2, int b){Â
    // Prints elements of the 1st subarray    for (int i = 0; i < a; i++)    {        Console.Write(g1[i] + " ");    }    Console.Write("and ");Â
    // Prints elements of the 2nd subarray    for (int i = 0; i < b; i++)     {        Console.Write(g2[i] + " ");    }    Console.WriteLine();}Â
// Function that returns true if // the sum of the elements of // arrays g1[] and g2[] is equalstatic bool checksum(int []g1, int a, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int []g2, int b){Â Â Â Â int i, x;Â
    // Adding elements of the 1st array    for (i = 0, x = 0; i < a; i++)     {        x += g1[i];    }Â
    // Subtracting elements of     // the 2nd array    for (i = 0; i < b; i++)    {        x -= g2[i];    }Â
    // If x is 0 then the sum of elements    // in both the arrays is equal    return (x == 0);}Â
// Function to find all valid subsequencesstatic void formgroups(int []arr, int x,                        int []g1, int a,                        int []g2, int b, int n){    // Base Case    if (x == n)     {Â
        // If sum of the two subsequences        // is equal then print the elements        if (checksum(g1, a, g2, b))         {Â
            // Print the subsequences            print(g1, a, g2, b);        }        return;    }Â
    // Recursive CaseÂ
    // Choose current element to be a    // part of the first subsequence    g1[a] = arr[x];    formgroups(arr, x + 1, g1,                     a + 1, g2, b, n);Â
    // Choose current element to be a    // part of the second subsequence    g2[b] = arr[x];    formgroups(arr, x + 1, g1, a,                 g2, b + 1, n);}Â
// Driver codepublic static void Main() {Â Â Â Â int []arr = { 1, 2, 3, 9, 4, 5 };Â Â Â Â int n = arr.Length;Â
    int []g1 = new int[MAX];    int []g2 = new int[MAX];    formgroups(arr, 0, g1, 0, g2, 0, n);}}Â
// This code is contributed by anuj_67... |
PHP
<?php// PHP implementation of the approachconst MAX = 100000; Â
// Function to print the subsequence elements function printi($g1, $a, $g2, $b) { Â
    // Prints elements of the 1st subarray     for ($i = 0; $i < $a; $i++)    {         echo ($g1[$i]);        echo " ";    }     echo ("and "); Â
    // Prints elements of the 2nd subarray     for ($i = 0; $i < $b; $i++)    {         echo ($g2[$i]);        echo " ";    }     echo "\n"; } Â
// Function that returns true if the sum of the // elements of arrays g1[] and g2[] is equal function checksum($g1, $a, $g2, $b) { Â
    // Adding elements of the 1st array     for ($i = 0, $x = 0; $i < $a; $i++)     {         $x += $g1[$i];     } Â
    // Subtracting elements of the 2nd array     for ($i = 0; $i < $b; $i++)     {         $x -= $g2[$i];     } Â
    // If x is 0 then the sum of elements     // in both the arrays is equal     return ($x == 0); } Â
// Function to find all valid subsequences function formgroups($arr, $x, $g1, $a,                           $g2, $b, $n) {     // Base Case     if ($x == $n)     { Â
        // If sum of the two subsequences         // is equal then print the elements         if (checksum($g1, $a, $g2, $b))         { Â
            // Print the subsequences             printi($g1, $a, $g2, $b);         }         return;     } Â
    // Recursive Case Â
    // Choose current element to be a     // part of the first subsequence     $g1[$a] = $arr[$x];     formgroups($arr, $x + 1, $g1,                $a + 1, $g2, $b, $n); Â
    // Choose current element to be a     // part of the second subsequence     $g2[$b] = $arr[$x];     formgroups($arr, $x + 1, $g1, $a,                 $g2, $b + 1, $n); } Â
// Driver code $arr = array(1, 2, 3, 9, 4, 5); $n = count($arr);Â
$g1 = array();$g2 = array();Â
formgroups($arr, 0, $g1, 0, $g2, 0, $n); Â
// This code is contributed by Naman_Garg.?> |
Javascript
<script>Â
// Javascript implementation of the approachvar MAX = 100000;Â
// Function to print the subsequence elementsfunction print(g1, a, g2, b){         // Prints elements of the 1st subarray    for(var i = 0; i < a; i++)    {        document.write( g1[i] + " ");    }    document.write("and ");Â
    // Prints elements of the 2nd subarray    for(var i = 0; i < b; i++)    {        document.write( g2[i] + " ");    }    document.write("<br>");}Â
// Function that returns true if the sum of the// elements of arrays g1[] and g2[] is equalfunction checksum(g1, a, g2, b){Â Â Â Â var i, x;Â
    // Adding elements of the 1st array    for(i = 0, x = 0; i < a; i++)     {        x += g1[i];    }Â
    // Subtracting elements of the 2nd array    for(i = 0; i < b; i++)    {        x -= g2[i];    }Â
    // If x is 0 then the sum of elements    // in both the arrays is equal    return (x == 0);}Â
// Function to find all valid subsequencesfunction formgroups(arr, x, g1, a, g2, b, n){         // Base Case    if (x == n)    {                 // If sum of the two subsequences        // is equal then print the elements        if (checksum(g1, a, g2, b))         {                         // Print the subsequences            print(g1, a, g2, b);        }        return;    }Â
    // Recursive CaseÂ
    // Choose current element to be a    // part of the first subsequence    g1[a] = arr[x];    formgroups(arr, x + 1, g1, a + 1,                g2, b, n);Â
    // Choose current element to be a    // part of the second subsequence    g2[b] = arr[x];    formgroups(arr, x + 1, g1, a, g2,                     b + 1, n);}Â
// Driver codevar arr = [ 1, 2, 3, 9, 4, 5 ];var n = arr.length;Â
var g1 = Array(MAX).fill(0), Â Â Â Â g2 = Array(MAX).fill(0);formgroups(arr, 0, g1, 0, g2, 0, n);Â
// This code is contributed by noob2000Â
</script> |
1 2 9 and 3 4 5 1 2 4 5 and 3 9 3 9 and 1 2 4 5 3 4 5 and 1 2 9
Â
Time Complexity: O(2n)
Auxiliary Space: O(n), where n is the length of the input array
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



