Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count ways to split array into pair of subsets with difference between their sum equal to K

  • Last Updated : 10 Nov, 2021

Given an array arr[] consisting of N integers and an integer K, the task is to find the number of ways to split the array into a pair of subsets such that the difference between their sum is K.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {1, 1, 2, 3}, K = 1
Output: 3
Explanation:
Following splits into a pair of subsets satisfies the given condition:  



  1. {1, 1, 2}, {3}, difference = (1 + 1 + 2) – 3 = 4 – 3 = 1.
  2. {1, 3} {1, 2}, difference = (1 + 3) – (1 + 2) = 4 – 3 = 1.
  3. {1, 3} {1, 2}, difference = (1 + 3) – (1 + 2) = 4 – 3 = 1.

Therefore, the count of ways to split is 3.
 

Input: arr[] = {1, 2, 3}, K = 2
Output: 1
Explanation:
The only possible split into a pair of subsets satisfying the given condition is {1, 3}, {2}, where the difference = (1 + 3) – 2 = 4 – 2 =2. 
Therefore, the count of ways to split is 1. 

Naive Approach: The simple approach to solve the given problem is to generate all the possible subsets and store the sum of each subset in an array say subset[]. Then, check if there exist any pair exists in the array subset[] whose difference is K. After checking for all the pairs, print the total count of such pairs as the result. 
Time Complexity: O(2N)
Auxiliary Space: O(2N)

Efficient Approach: The above approach can be optimized using the following observations.

Let the sum of the first and second subsets be S1 and S2 respectively, and the sum of array elements be Y.

Now, the sum of both the subsets must be equal to the sum of the array elements. 
Therefore, S1 + S2 = Y — (1)
To satisfy the given condition, their difference must be equal to K.
Therefore, S1 – S2 = K — (2)
Adding (1) & (2), the equation obtained is 
S1 = (K + Y)/2 — (3)

Therefore, for a pair of subsets having sums S1 and S2, equation (3) must hold true, i.e., the sum of elements of the subset must be equal to (K + Y)/2. Now, the problem reduces to counting the number of subsets with a given sum. This problem can be solved using Dynamic Programming, whose recurrence relation is as follows:

dp[i][C] = dp[i + 1][C – arr[i]] + dp[i + 1][C]

Here, dp[i][C] stores the number of subsets of the subarray arr[i … N – 1], such that their sum is equal to C.
Thus, the recurrence is very trivial as there are only two choices i.e., either consider the ith array element in the subset or don’t.

Below is the implementation of the above approach :

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
#define maxN 20
#define maxSum 50
#define minSum 50
#define base 50
 
// To store the states of DP
int dp[maxN][maxSum + minSum];
bool v[maxN][maxSum + minSum];
 
// Function to find count of subsets
// with a given sum
int findCnt(int* arr, int i,
            int required_sum,
            int n)
{
    // Base case
    if (i == n) {
        if (required_sum == 0)
            return 1;
        else
            return 0;
    }
 
    // If an already computed
    // subproblem occurs
    if (v[i][required_sum + base])
        return dp[i][required_sum + base];
 
    // Set the state as solved
    v[i][required_sum + base] = 1;
 
    // Recurrence relation
    dp[i][required_sum + base]
        = findCnt(arr, i + 1,
                  required_sum, n)
          + findCnt(arr, i + 1,
                    required_sum - arr[i], n);
    return dp[i][required_sum + base];
}
 
// Function to count ways to split array into
// pair of subsets with difference K
void countSubsets(int* arr, int K,
                  int n)
{
 
    // Store the total sum of
    // element of the array
    int sum = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // Calculate sum of array elements
        sum += arr[i];
    }
 
    // Store the required sum
    int S1 = (sum + K) / 2;
 
    // Print the number of subsets
    // with sum equal to S1
    cout << findCnt(arr, 0, S1, n);
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 1, 2, 3 };
    int N = sizeof(arr) / sizeof(int);
    int K = 1;
 
    // Function Call
    countSubsets(arr, K, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG
{
  static int maxN = 20;
  static int maxSum = 50;
  static int minSum = 50;
  static int Base = 50;
 
  // To store the states of DP
  static int[][] dp = new int[maxN][maxSum + minSum];
  static boolean[][] v = new boolean[maxN][maxSum + minSum];
 
  // Function to find count of subsets
  // with a given sum
  static int findCnt(int[] arr, int i,
                     int required_sum,
                     int n)
  {
    // Base case
    if (i == n) {
      if (required_sum == 0)
        return 1;
      else
        return 0;
    }
 
    // If an already computed
    // subproblem occurs
    if (v[i][required_sum + Base])
      return dp[i][required_sum + Base];
 
    // Set the state as solved
    v[i][required_sum + Base] = true;
 
    // Recurrence relation
    dp[i][required_sum + Base]
      = findCnt(arr, i + 1,
                required_sum, n)
      + findCnt(arr, i + 1,
                required_sum - arr[i], n);
    return dp[i][required_sum + Base];
  }  
 
  // Function to count ways to split array into
  // pair of subsets with difference K
  static void countSubsets(int[] arr, int K,
                           int n)
  {
    // Store the total sum of
    // element of the array
    int sum = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++)
    {
 
      // Calculate sum of array elements
      sum += arr[i];
    }
 
    // Store the required sum
    int S1 = (sum + K) / 2;
 
    // Print the number of subsets
    // with sum equal to S1
    System.out.print(findCnt(arr, 0, S1, n));
  
 
 
  // Driver Code
  public static void main(String[] args)
  {
    int[] arr = { 1, 1, 2, 3 };
    int N = arr.length;
    int K = 1;
 
    // Function Call
    countSubsets(arr, K, N);
  }
}
 
// This code is contributed by sanjoy_62.

Python3




# Python program for the above approach
maxN = 20;
maxSum = 50;
minSum = 50;
Base = 50;
 
# To store the states of DP
dp = [[0 for i in range(maxSum + minSum)] for j in range(maxN)];
v = [[False for i in range(maxSum + minSum)] for j in range(maxN)];
 
# Function to find count of subsets
# with a given sum
def findCnt(arr, i, required_sum, n):
   
    # Base case
    if (i == n):
        if (required_sum == 0):
            return 1;
        else:
            return 0;
 
    # If an already computed
    # subproblem occurs
    if (v[i][required_sum + Base]):
        return dp[i][required_sum + Base];
 
    # Set the state as solved
    v[i][required_sum + Base] = True;
 
    # Recurrence relation
    dp[i][required_sum + Base] = findCnt(arr, i + 1, required_sum, n)\
    + findCnt(arr, i + 1, required_sum - arr[i], n);
    return dp[i][required_sum + Base];
 
# Function to count ways to split array into
# pair of subsets with difference K
def countSubsets(arr, K, n):
   
    # Store the total sum of
    # element of the array
    sum = 0;
 
    # Traverse the array
    for i in range(n):
       
        # Calculate sum of array elements
        sum += arr[i];
 
    # Store the required sum
    S1 = (sum + K) // 2;
 
    # Print the number of subsets
    # with sum equal to S1
    print(findCnt(arr, 0, S1, n));
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 1, 2, 3];
    N = len(arr);
    K = 1;
 
    # Function Call
    countSubsets(arr, K, N);
 
    # This code is contributed by shikhasingrajput

C#




// C# program for the above approach
using System;
class GFG {
     
    static int maxN = 20;
    static int maxSum = 50;
    static int minSum = 50;
    static int Base = 50;
     
    // To store the states of DP
    static int[,] dp = new int[maxN, maxSum + minSum];
    static bool[,] v = new bool[maxN, maxSum + minSum];
       
    // Function to find count of subsets
    // with a given sum
    static int findCnt(int[] arr, int i,
                int required_sum,
                int n)
    {
        // Base case
        if (i == n) {
            if (required_sum == 0)
                return 1;
            else
                return 0;
        }
       
        // If an already computed
        // subproblem occurs
        if (v[i, required_sum + Base])
            return dp[i, required_sum + Base];
       
        // Set the state as solved
        v[i,required_sum + Base] = true;
       
        // Recurrence relation
        dp[i,required_sum + Base]
            = findCnt(arr, i + 1,
                      required_sum, n)
              + findCnt(arr, i + 1,
                        required_sum - arr[i], n);
        return dp[i,required_sum + Base];
    }
       
    // Function to count ways to split array into
    // pair of subsets with difference K
    static void countSubsets(int[] arr, int K,
                      int n)
    {
       
        // Store the total sum of
        // element of the array
        int sum = 0;
       
        // Traverse the array
        for (int i = 0; i < n; i++)
        {
       
            // Calculate sum of array elements
            sum += arr[i];
        }
       
        // Store the required sum
        int S1 = (sum + K) / 2;
       
        // Print the number of subsets
        // with sum equal to S1
        Console.Write(findCnt(arr, 0, S1, n));
    }  
 
  // Driver code
  static void Main()
  {
    int[] arr = { 1, 1, 2, 3 };
    int N = arr.Length;
    int K = 1;
   
    // Function Call
    countSubsets(arr, K, N);
  }
}
 
// This code is contributed by divyeshrabadiya07.

Javascript




<script>
 
// Javascript program for the above approach
 
var maxN = 20;
var maxSum = 50;
var minSum = 50;
var base = 50;
 
// To store the states of DP
var dp = Array.from(Array(maxN),()=> Array(maxSum+minSum));
var v = Array.from(Array(maxN), ()=> Array(maxSum+minSum));
 
// Function to find count of subsets
// with a given sum
function findCnt(arr, i, required_sum, n)
{
    // Base case
    if (i == n) {
        if (required_sum == 0)
            return 1;
        else
            return 0;
    }
 
    // If an already computed
    // subproblem occurs
    if (v[i][required_sum + base])
        return dp[i][required_sum + base];
 
    // Set the state as solved
    v[i][required_sum + base] = 1;
 
    // Recurrence relation
    dp[i][required_sum + base]
        = findCnt(arr, i + 1,
                required_sum, n)
        + findCnt(arr, i + 1,
                    required_sum - arr[i], n);
    return dp[i][required_sum + base];
}
 
// Function to count ways to split array into
// pair of subsets with difference K
function countSubsets(arr, K, n)
{
 
    // Store the total sum of
    // element of the array
    var sum = 0;
 
    // Traverse the array
    for (var i = 0; i < n; i++) {
 
        // Calculate sum of array elements
        sum += arr[i];
    }
 
    // Store the required sum
    var S1 = (sum + K) / 2;
 
    // Print the number of subsets
    // with sum equal to S1
    document.write( findCnt(arr, 0, S1, n));
}
 
// Driver Code
var arr = [ 1, 1, 2, 3 ];
var N = arr.length;
var K = 1;
// Function Call
countSubsets(arr, K, N);
 
 
</script>
Output: 
3

 

Time Complexity: O(N*K) 
Auxiliary Space: O(N*K) 
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!