Count ways to split array into pair of subsets with difference between their sum equal to K
Last Updated :
23 Jul, 2025
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:
Input: arr[] = {1, 1, 2, 3}, K = 1
Output: 3
Explanation:
Following splits into a pair of subsets satisfies the given condition:
- {1, 1, 2}, {3}, difference = (1 + 1 + 2) - 3 = 4 - 3 = 1.
- {1, 3} {1, 2}, difference = (1 + 3) - (1 + 2) = 4 - 3 = 1.
- {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>
Time Complexity: O(N*K)
Auxiliary Space: O(N*K)
Efficient approach : Using DP Tabulation method ( Iterative approach )
The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memorization(top-down) because memorization method needs extra stack space of recursion calls.
Steps to solve this problem :
- Calculate the total sum of elements in the given array.
- Calculate the value of S1 using the formula (sum + K) / 2, where K is the given difference.
- Create a 2D dp array of size (n+1)x(S1+1), where n is the size of the given array.
- Initialize the base case of dp[i][0] as 1 for all i from 0 to n.
- Fill the dp array using the choice diagram approach. For each element in the array, we have two choices: include it or exclude it. If we include it, we reduce the sum by the value of that element, and if we exclude it, we leave the sum as it is. So, we update the dp array accordingly.
- Return the value of dp[n][S1], which represents the count of subsets with the required sum S1.
Implementation :
C++
// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count ways to split array into
// pair of subsets with difference K
int countSubsets(int* arr, int K, int n) {
// Calculate total sum of elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// Calculate S1 using given formula
int S1 = (sum + K) / 2;
// Create dp array of size (n+1)x(S1+1)
vector<vector<int>> dp(n+1, vector<int>(S1+1, 0));
// Base case initialization
for (int i = 0; i <= n; i++)
dp[i][0] = 1;
// Choice diagram iterative filling
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= S1; j++) {
if (arr[i-1] <= j) {
dp[i][j] = dp[i-1][j] + dp[i-1][j-arr[i-1]];
}
else {
dp[i][j] = dp[i-1][j];
}
}
}
// Return count of subsets with sum S1
return dp[n][S1];
}
// Driver Code
int main() {
int arr[] = {1, 1, 2, 3};
int N = sizeof(arr) / sizeof(int);
int K = 1;
// Function Call
cout << countSubsets(arr, K, N) << endl;
return 0;
}
// this code is contributed by bhardwajji
Java
import java.util.*;
class Main
{
// Function to count ways to split array into
// pair of subsets with difference K
static int countSubsets(int[] arr, int K, int n)
{
// Calculate total sum of elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// Calculate S1 using given formula
int S1 = (sum + K) / 2;
// Create dp array of size (n+1)x(S1+1)
int[][] dp = new int[n+1][S1+1];
// Base case initialization
for (int i = 0; i <= n; i++)
dp[i][0] = 1;
// Choice diagram iterative filling
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= S1; j++) {
if (arr[i-1] <= j) {
dp[i][j] = dp[i-1][j] + dp[i-1][j-arr[i-1]];
}
else {
dp[i][j] = dp[i-1][j];
}
}
}
// Return count of subsets with sum S1
return dp[n][S1];
}
// Driver Code
public static void main(String[] args) {
int[] arr = {1, 1, 2, 3};
int N = arr.length;
int K = 1;
// Function Call
System.out.println(countSubsets(arr, K, N));
}
}
Python3
# Python program for above approach
# Function to count ways to split array into
# pair of subsets with difference K
def countSubsets(arr, K, n):
# Calculate total sum of elements
sum = 0
for i in range(n):
sum += arr[i]
# Calculate S1 using given formula
S1 = (sum + K) // 2
# Create dp array of size (n+1)x(S1+1)
dp = [[0 for j in range(S1+1)] for i in range(n+1)]
# Base case initialization
for i in range(n+1):
dp[i][0] = 1
# Choice diagram iterative filling
for i in range(1, n+1):
for j in range(S1+1):
if arr[i-1] <= j:
dp[i][j] = dp[i-1][j] + dp[i-1][j-arr[i-1]]
else:
dp[i][j] = dp[i-1][j]
# Return count of subsets with sum S1
return dp[n][S1]
# Driver Code
if __name__ == '__main__':
arr = [1, 1, 2, 3]
N = len(arr)
K = 1
# Function Call
print(countSubsets(arr, K, N))
C#
using System;
class GFG {
// Function to count ways to split array into
// pair of subsets with difference K
static int countSubsets(int[] arr, int K, int n)
{
// Calculate total sum of elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// Calculate S1 using given formula
int S1 = (sum + K) / 2;
// Create dp array of size (n+1)x(S1+1)
int[, ] dp = new int[n + 1, S1 + 1];
// Base case initialization
for (int i = 0; i <= n; i++)
dp[i, 0] = 1;
// Choice diagram iterative filling
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= S1; j++) {
if (arr[i - 1] <= j) {
dp[i, j] = dp[i - 1, j]
+ dp[i - 1, j - arr[i - 1]];
}
else {
dp[i, j] = dp[i - 1, j];
}
}
}
// Return count of subsets with sum S1
return dp[n, S1];
}
// Driver Code
static void Main()
{
int[] arr = { 1, 1, 2, 3 };
int N = arr.Length;
int K = 1;
// Function Call
Console.WriteLine(countSubsets(arr, K, N));
}
}
// This code is contributed by user_dtewbxkn77n
JavaScript
// Javascript code addition
function countSubsets(arr, K, n)
{
// Calculate total sum of elements
let sum = 0;
for (let i = 0; i < n; i++) {
sum += arr[i];
}
// Calculate S1 using given formula
let S1 = Math.floor((sum + K) / 2);
// Create dp array of size (n+1)x(S1+1)
let dp = new Array(n + 1).fill().map(() => new Array(S1 + 1).fill(0));
// Base case initialization
for (let i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// Choice diagram iterative filling
for (let i = 1; i <= n; i++) {
for (let j = 0; j <= S1; j++) {
if (arr[i - 1] <= j) {
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - arr[i - 1]];
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
// Return count of subsets with sum S1
return dp[n][S1];
}
// Driver Code
const arr = [1, 1, 2, 3];
const N = arr.length;
const K = 1;
// Function Call
console.log(countSubsets(arr, K, N));
// The code is contributed by Arushi Goel.
Time Complexity: O(N*k)
Auxiliary Space: O(N*K)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem