Count of subsets with sum equal to X | Set-2
Last Updated :
23 Jul, 2025
Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X.
Examples:
Input: arr[] = {1, 2, 3, 3}, X = 6
Output: 3
Explanation: All the possible subsets are {1, 2, 3}, {1, 2, 3} and {3, 3}.
Input: arr[] = {1, 1, 1, 1}, X = 1
Output: 4
Space Efficient Approach: This problem has already been discussed in the article here. This article focuses on a similar Dynamic Programming approach which uses only O(X) space. The standard DP relation of solving this problem as discussed in the above article is:
dp[i][C] = dp[i – 1][C – arr[i]] + dp[i – 1][C]
where dp[i][C] stores the number of subsets of the subarray arr[0… i] such that their sum is equal to C. It can be noted that the dp[i]th state only requires the array values of the dp[i - 1]th state. Hence the above relation can be simplified into the following:
dp[C] = dp[C - arr[i]] + dp[C]
Here, a good point to note is that during the calculation of dp[C], the variable C must be iterated in decreasing order in order to avoid the duplicity of arr[i] in the subset-sum count.
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the count of subsets
// having the given sum
int subsetSum(int arr[], int n, int sum)
{
// Initializing the dp-table
int dp[sum + 1] = {};
// Case for sum of elements in empty set
dp[0] = 1;
// Loop to iterate over array elements
for (int i = 0; i < n; i++) {
for (int j = sum; j >= 0; j--) {
// If j-arr[i] is a valid index
if (j - arr[i] >= 0) {
dp[j] = dp[j - arr[i]] + dp[j];
}
}
}
// Return answer
return dp[sum];
}
// Driven Code
int main()
{
int arr[] = { 1, 1, 1, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
int sum = 1;
cout << subsetSum(arr, N, sum) << endl;
return 0;
}
Java
// Java implementation of the above approach
import java.util.*;
public class GFG
{
// Function to find the count of subsets
// having the given sum
static int subsetSum(int arr[], int n, int sum)
{
// Initializing the dp-table
int dp[] = new int[sum + 1];
// Case for sum of elements in empty set
dp[0] = 1;
// Loop to iterate over array elements
for (int i = 0; i < n; i++) {
for (int j = sum; j >= 0; j--) {
// If j-arr[i] is a valid index
if (j - arr[i] >= 0) {
dp[j] = dp[j - arr[i]] + dp[j];
}
}
}
// Return answer
return dp[sum];
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 1, 1, 1 };
int N = arr.length;
int sum = 1;
System.out.println(subsetSum(arr, N, sum));
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python implementation of the above approach
# Function to find the count of subsets
# having the given sum
def subsetSum(arr, n, sum):
# Initializing the dp-table
dp = [0] * (sum + 1)
# Case for sum of elements in empty set
dp[0] = 1;
# Loop to iterate over array elements
for i in range(n):
for j in range(sum, 0, -1):
# If j-arr[i] is a valid index
if (j - arr[i] >= 0):
dp[j] = dp[j - arr[i]] + dp[j];
# Return answer
return dp[sum];
# Driven Code
arr = [1, 1, 1, 1];
N = len(arr)
sum = 1;
print(subsetSum(arr, N, sum))
# This code is contributed by gfgking.
C#
// C# implementation of the above approach
using System;
public class GFG
{
// Function to find the count of subsets
// having the given sum
static int subsetSum(int []arr, int n, int sum)
{
// Initializing the dp-table
int []dp = new int[sum + 1];
// Case for sum of elements in empty set
dp[0] = 1;
// Loop to iterate over array elements
for (int i = 0; i < n; i++) {
for (int j = sum; j >= 0; j--) {
// If j-arr[i] is a valid index
if (j - arr[i] >= 0) {
dp[j] = dp[j - arr[i]] + dp[j];
}
}
}
// Return answer
return dp[sum];
}
// Driver code
public static void Main(String []args)
{
int []arr = { 1, 1, 1, 1 };
int N = arr.Length;
int sum = 1;
Console.WriteLine(subsetSum(arr, N, sum));
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// Javascript implementation of the above approach
// Function to find the count of subsets
// having the given sum
function subsetSum(arr, n, sum)
{
// Initializing the dp-table
let dp = new Array(sum + 1).fill(0)
// Case for sum of elements in empty set
dp[0] = 1;
// Loop to iterate over array elements
for (let i = 0; i < n; i++) {
for (let j = sum; j >= 0; j--) {
// If j-arr[i] is a valid index
if (j - arr[i] >= 0) {
dp[j] = dp[j - arr[i]] + dp[j];
}
}
}
// Return answer
return dp[sum];
}
// Driven Code
let arr = [1, 1, 1, 1];
let N = arr.length;
let sum = 1;
document.write(subsetSum(arr, N, sum))
// This code is contributed by gfgking.
</script>
Time Complexity: O(N * X)
Auxiliary Space: O(X)
Another Approach (Memoised dynamic programming):
The problem can be solved using memoised dynamic programming. We can create a 2D dp array where dp[i][j] represents the number of subsets of arr[0...i] with sum equal to j. The recursive relation for dp[i][j] can be defined as follows:
- If i = 0, dp[0][j] = 1 if arr[0] == j else 0
- If i > 0, dp[i][j] = dp[i-1][j] + dp[i-1][j-arr[i]], if j >= arr[i]
- If i > 0, dp[i][j] = dp[i-1][j], if j < arr[i]
The base case for i = 0 can be easily computed as the subset containing only the first element of the array has a sum equal to arr[0] and no other sum. For all other i > 0, we need to consider two cases: either the ith element is included in a subset with sum j, or it is not included. If it is not included, we need to find the number of subsets of arr[0...(i-1)] with sum equal to j. If it is included, we need to find the number of subsets of arr[0...(i-1)] with sum equal to (j - arr[i]).
The final answer will be stored in dp[N-1][X], as we need to find the number of subsets of arr[0...N-1] with sum equal to X.
Algorithm:
- Define a recursive function countSubsets(arr, X, dp, i, sum) that takes the following parameters:
- arr: The input array
- X: The target sum
- dp: The memoization table
- i: The index of the current element being considered
- sum: The current sum of elements in the subset
- If i is less than 0, return 1 if sum is equal to X, otherwise return 0
- If dp[i][sum] is not equal to -1, return dp[i][sum]
- Initialize ans to countSubsets(arr, X, dp, i - 1, sum)
- If sum plus the ith element of arr is less than or equal to X, add countSubsets(arr, X, dp, i - 1, sum + arr[i]) to ans
- Set dp[i][sum] to ans
- Return ans
- Initialize the DP table dp to all -1 values
- Call countSubsets(arr, X, dp, arr.size() - 1, 0) and store the result in ans
- Print ans as the number of subsets with a sum equal to X in arr
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Recursive function to count subsets with a sum equal to X
int countSubsets(vector<int>& arr, int X, vector<vector<int>> &dp, int i, int sum) {
// Base case: if we have reached the end of the array
if (i < 0) {
// If the sum is equal to X, return 1, else return 0
return (sum == X ? 1 : 0);
}
// If the subproblem has already been solved, return the solution
if (dp[i][sum] != -1) {
return dp[i][sum];
}
// If we don't include the current element in the subset
int ans = countSubsets(arr, X, dp, i - 1, sum);
// If we include the current element in the subset
if (sum + arr[i] <= X) {
ans += countSubsets(arr, X, dp, i - 1, sum + arr[i]);
}
// Memoize the solution to the subproblem
dp[i][sum] = ans;
// Return the solution to the current subproblem
return ans;
}
int main() {
// Example usage
vector<int> arr = { 1, 1, 1, 1 };
int X = 1;
// Initialize the DP table with -1
vector<vector<int>> dp(arr.size()+1, vector<int>(X+1, -1));
// Count the number of subsets with a sum equal to X
int ans = countSubsets(arr, X, dp, arr.size() - 1, 0);
// Print the result
cout << ans << endl;
return 0;
}
Java
// Java implementation
import java.util.*;
public class Main {
// Recursive function to count subsets with a sum equal to X
public static int countSubsets(List<Integer> arr, int X, int[][] dp, int i, int sum) {
// Base case: if we have reached the end of the array
if (i < 0) {
// If the sum is equal to X, return 1, else return 0
return (sum == X ? 1 : 0);
}
// If the subproblem has already been solved, return the solution
if (dp[i][sum] != -1) {
return dp[i][sum];
}
// If we don't include the current element in the subset
int ans = countSubsets(arr, X, dp, i - 1, sum);
// If we include the current element in the subset
if (sum + arr.get(i) <= X) {
ans += countSubsets(arr, X, dp, i - 1, sum + arr.get(i));
}
// Memoize the solution to the subproblem
dp[i][sum] = ans;
// Return the solution to the current subproblem
return ans;
}
public static void main(String[] args) {
// Example usage
List<Integer> arr = Arrays.asList(1, 1, 1, 1);
int X = 1;
// Initialize the DP table with -1
int[][] dp = new int[arr.size() + 1][X + 1];
for (int i = 0; i <= arr.size(); i++) {
Arrays.fill(dp[i], -1);
}
// Count the number of subsets with a sum equal to X
int ans = countSubsets(arr, X, dp, arr.size() - 1, 0);
// Print the result
System.out.println(ans);
}
}
// This code is contributed by Sakshi
Python3
# Recursive function to count subsets with a sum equal to X
def count_subsets(arr, X, dp, i, sum):
# Base case: if we have reached the end of the array
if i < 0:
# If the sum is equal to X, return 1, else return 0
return 1 if sum == X else 0
# If the subproblem has already been solved, return the solution
if dp[i][sum] != -1:
return dp[i][sum]
# If we don't include the current element in the subset
ans = count_subsets(arr, X, dp, i - 1, sum)
# If we include the current element in the subset
if sum + arr[i] <= X:
ans += count_subsets(arr, X, dp, i - 1, sum + arr[i])
# Memoize the solution to the subproblem
dp[i][sum] = ans
# Return the solution to the current subproblem
return ans
if __name__ == "__main__":
# Example usage
arr = [1, 1, 1, 1]
X = 1
# Initialize the DP table with -1
dp = [[-1 for _ in range(X + 1)] for _ in range(len(arr) + 1)]
# Count the number of subsets with a sum equal to X
ans = count_subsets(arr, X, dp, len(arr) - 1, 0)
# Print the result
print(ans)
C#
using System;
using System.Collections.Generic;
class Program
{
// Recursive function to count subsets with a sum equal to X
static int CountSubsets(List<int> arr, int X, int[,] dp, int i, int sum)
{
// Base case: if we have reached the end of the array
if (i < 0)
{
// If the sum is equal to X, return 1, else return 0
return (sum == X ? 1 : 0);
}
// If the subproblem has already been solved, return the solution
if (dp[i, sum] != -1)
{
return dp[i, sum];
}
// If we don't include the current element in the subset
int ans = CountSubsets(arr, X, dp, i - 1, sum);
// If we include the current element in the subset
if (sum + arr[i] <= X)
{
ans += CountSubsets(arr, X, dp, i - 1, sum + arr[i]);
}
// Memoize the solution to the subproblem
dp[i, sum] = ans;
// Return the solution to the current subproblem
return ans;
}
static void Main(string[] args)
{
// Example usage
List<int> arr = new List<int> { 1, 1, 1, 1 };
int X = 1;
// Initialize the DP table with -1
int[,] dp = new int[arr.Count + 1, X + 1];
for (int i = 0; i <= arr.Count; i++)
{
for (int j = 0; j <= X; j++)
{
dp[i, j] = -1;
}
}
// Count the number of subsets with a sum equal to X
int ans = CountSubsets(arr, X, dp, arr.Count - 1, 0);
// Print the result
Console.WriteLine(ans);
}
}
JavaScript
// Recursive function to count subsets with a sum equal to X
const countSubsets = (arr, X, dp, i, sum) => {
// Base case: if we have reached the end of the array
if (i < 0) {
return (sum === X ? 1 : 0);
}
// If the subproblem has already been solved, return the solution
if (dp[i][sum] !== -1) {
return dp[i][sum];
}
// If we don't include the current element in the subset
let ans = countSubsets(arr, X, dp, i - 1, sum);
// If we include the current element in the subset
if (sum + arr[i] <= X) {
ans += countSubsets(arr, X, dp, i - 1, sum + arr[i]);
}
// Memoize the solution to the subproblem
dp[i][sum] = ans;
// Return the solution to the current subproblem
return ans;
};
// Driver code
const arr = [1, 1, 1, 1];
const X = 1;
const dp = new Array(arr.length + 1).fill().map(() => new Array(X + 1).fill(-1));
const ans = countSubsets(arr, X, dp, arr.length - 1, 0);
console.log(ans);
Time Complexity: O(N * X), where N is the size of the array and X is the target sum. This is because each subproblem is solved only once, and there are N * X possible subproblems.
Auxiliary Space: O(N * X), as we are using a 2D array of size (N + 1) * (X + 1) to store the solutions to the subproblems.
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