Given an array of size n and an integer m, the task is to find the number of non-empty subsequences such that the sum of the subsequence is divisible by m.
Note:
- The sum of all array elements in small, i.e., it is within integer range.
- m > 0.
Examples:
Input : arr[] = [1, 2, 3, 4], m = 2
Output : 7
Explanation: The subsequences are [1, 3], [1, 3, 4], [1, 2, 3], [1, 2, 3, 4], [2], [2, 4], and [4].Input : arr[] = [1, 2, 3], m = 3
Output : 3
Explanation: The subsequences are [1, 2], [1, 2, 3], [3].
[Naive Approach] Using Recursion - O(2^n) time and O(n) space
The idea is to recursively generate all the possible subsets. For every subset, compute its sum, and if the sum is multiple of m, increment result by 1. Finally, decrement the result value by 1 as empty subset is also counted in this approach.
Recurrence relation:
- subCount(i, sum, m, arr) = subCount(i+1, sum+arr[i], m, arr) + subCount(i+1, sum, m, arr).
Base Case:
- For i == n, subCount(i, sum, m, arr) = 1 if sum % m == 0, 0 otherwise.
// C++ program to find Number of
// subsets with sum divisible by m
#include <bits/stdc++.h>
using namespace std;
// Recursive function which finds the number of subsequences
// starting from index i and current sum.
int subCountRecur(int i, int sum, int m, vector<int> &arr) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.size()) {
return (sum % m == 0)?1:0;
}
// Include current element in subset
int take = subCountRecur(i+1, sum+arr[i], m, arr);
// Exclude current element
int noTake = subCountRecur(i+1, sum, m, arr);
return take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
int subCount(vector<int> &arr, int m) {
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr) - 1;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
int m = 2;
cout << subCount(arr, m);
return 0;
}
// Java program to find Number of
// subsets with sum divisible by m
import java.util.*;
class GfG {
// Recursive function which finds the number of subsequences
// starting from index i and current sum.
static int subCountRecur(int i, int sum, int m, int[] arr) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.length) {
return (sum % m == 0) ? 1 : 0;
}
// Include current element in subset
int take = subCountRecur(i + 1, sum + arr[i], m, arr);
// Exclude current element
int noTake = subCountRecur(i + 1, sum, m, arr);
return take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr) - 1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
System.out.println(subCount(arr, m));
}
}
# Python program to find Number of
# subsets with sum divisible by m
# Recursive function which finds the number of subsequences
# starting from index i and current sum.
def subCountRecur(i, sum, m, arr):
# Base case: End of array
# Check if sum is divisible by m
if i == len(arr):
return 1 if sum % m == 0 else 0
# Include current element in subset
take = subCountRecur(i + 1, sum + arr[i], m, arr)
# Exclude current element
noTake = subCountRecur(i + 1, sum, m, arr)
return take + noTake
# Function which finds Number of
# subsets with sum divisible by m
def subCount(arr, m):
# Decrement 1 from answer as empty
# subsequence is also counted.
return subCountRecur(0, 0, m, arr) - 1
if __name__ == "__main__":
arr = [1, 2, 3, 4]
m = 2
print(subCount(arr, m))
// C# program to find Number of
// subsets with sum divisible by m
using System;
class GfG {
// Recursive function which finds the number of subsequences
// starting from index i and current sum.
static int subCountRecur(int i, int sum, int m, int[] arr) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.Length) {
return (sum % m == 0) ? 1 : 0;
}
// Include current element in subset
int take = subCountRecur(i + 1, sum + arr[i], m, arr);
// Exclude current element
int noTake = subCountRecur(i + 1, sum, m, arr);
return take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr) - 1;
}
static void Main(string[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
Console.WriteLine(subCount(arr, m));
}
}
// JavaScript program to find Number of
// subsets with sum divisible by m
// Recursive function which finds the number of subsequences
// starting from index i and current sum.
function subCountRecur(i, sum, m, arr) {
// Base case: End of array
// Check if sum is divisible by m
if (i === arr.length) {
return (sum % m === 0) ? 1 : 0;
}
// Include current element in subset
let take = subCountRecur(i + 1, sum + arr[i], m, arr);
// Exclude current element
let noTake = subCountRecur(i + 1, sum, m, arr);
return take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
function subCount(arr, m) {
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr) - 1;
}
let arr = [1, 2, 3, 4];
let m = 2;
console.log(subCount(arr, m));
Output
7
[Better Approach - 1] Using Top-Down DP (Memoization) – O(sum*n) time and O(sum*n) space
Optimal Substructure: Number of subsequences with sum divisible by m starting at index i and sum depends on the subproblems subCount(i+1, sum+arr[i], m) and subCount(i+1, sum, m). By solving these subproblems, we can determine the result for the current state.
Overlapping Subproblems: Recursive calls often compute the same (i, sum) states multiple times. To avoid recomputation, we store results in a 2D memo table.
- Since recursion changes with
iandsum, create a 2D memo table of size n * (sum + 1). memo[i][j]stores the number of subsequences starting from indexiwith current sumj.- Before computing a state, check if it is already stored in
memo. If yes, return it. - Subtract 1 from the final result to exclude the empty subsequence.
// C++ program to find Number of
// subsets with sum divisible by m
#include <bits/stdc++.h>
using namespace std;
// Memoized function which finds the number of subsequences
// starting from index i and current sum.
int subCountRecur(int i, int sum, int m, vector<int> &arr,
vector<vector<int>> &memo) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.size()) {
return (sum % m == 0) ? 1 : 0;
}
// If this state has already been computed,
// return the stored result
if (memo[i][sum] != -1) {
return memo[i][sum];
}
// Include current element in subset
int take = subCountRecur(i+1, sum+arr[i], m, arr, memo);
// Exclude current element
int noTake = subCountRecur(i+1, sum, m, arr, memo);
// Store and return the result
return memo[i][sum] = take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
int subCount(vector<int> &arr, int m) {
int n = arr.size();
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
// Initialize memoization table with -1
vector<vector<int>> memo(arr.size(), vector<int>(totalSum + 1, -1));
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr, memo) - 1;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
int m = 2;
cout << subCount(arr, m);
return 0;
}
// Java program to find Number of
// subsets with sum divisible by m
import java.util.*;
class GfG {
// Memoized function which finds the number of subsequences
// starting from index i and current sum.
static int subCountRecur(int i, int sum, int m,
int[] arr, int[][] memo) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.length) {
return (sum % m == 0) ? 1 : 0;
}
// If this state has already been computed,
// return the stored result
if (memo[i][sum] != -1) {
return memo[i][sum];
}
// Include current element in subset
int take = subCountRecur(i + 1, sum + arr[i], m, arr, memo);
// Exclude current element
int noTake = subCountRecur(i + 1, sum, m, arr, memo);
// Store and return the result
return memo[i][sum] = take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.length;
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
// Initialize memoization table with -1
int[][] memo = new int[n][totalSum + 1];
for (int i = 0; i < n; i++) {
Arrays.fill(memo[i], -1);
}
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr, memo) - 1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
System.out.println(subCount(arr, m));
}
}
# Python program to find Number of
# subsets with sum divisible by m
# Memoized function which finds the number of subsequences
# starting from index i and current sum.
def subCountRecur(i, sum, m, arr, memo):
# Base case: End of array
# Check if sum is divisible by m
if i == len(arr):
return 1 if sum % m == 0 else 0
# If this state has already been computed,
# return the stored result
if memo[i][sum] != -1:
return memo[i][sum]
# Include current element in subset
take = subCountRecur(i + 1, sum + arr[i], m, arr, memo)
# Exclude current element
noTake = subCountRecur(i + 1, sum, m, arr, memo)
# Store and return the result
memo[i][sum] = take + noTake
return memo[i][sum]
# Function which finds Number of
# subsets with sum divisible by m
def subCount(arr, m):
n = len(arr)
# Calculate total sum of array
totalSum = sum(arr)
# Initialize memoization table with -1
memo = [[-1 for _ in range(totalSum + 1)] for _ in range(n)]
# Decrement 1 from answer as empty
# subsequence is also counted.
return subCountRecur(0, 0, m, arr, memo) - 1
if __name__ == "__main__":
arr = [1, 2, 3, 4]
m = 2
print(subCount(arr, m))
// C# program to find Number of
// subsets with sum divisible by m
using System;
class GfG {
// Memoized function which finds the number of subsequences
// starting from index i and current sum.
static int subCountRecur(int i, int sum, int m,
int[] arr, int[,] memo) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.Length) {
return (sum % m == 0) ? 1 : 0;
}
// If this state has already been computed,
// return the stored result
if (memo[i, sum] != -1) {
return memo[i, sum];
}
// Include current element in subset
int take = subCountRecur(i + 1, sum + arr[i], m, arr, memo);
// Exclude current element
int noTake = subCountRecur(i + 1, sum, m, arr, memo);
// Store and return the result
return memo[i, sum] = take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.Length;
// Calculate total sum of array
int totalSum = 0;
foreach (int num in arr) {
totalSum += num;
}
// Initialize memoization table with -1
int[,] memo = new int[n, totalSum + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= totalSum; j++) {
memo[i, j] = -1;
}
}
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr, memo) - 1;
}
static void Main(string[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
Console.WriteLine(subCount(arr, m));
}
}
// JavaScript program to find Number of
// subsets with sum divisible by m
// Memoized function which finds the number of subsequences
// starting from index i and current sum.
function subCountRecur(i, sum, m, arr, memo) {
// Base case: End of array
// Check if sum is divisible by m
if (i === arr.length) {
return (sum % m === 0) ? 1 : 0;
}
// If this state has already been computed,
// return the stored result
if (memo[i][sum] !== -1) {
return memo[i][sum];
}
// Include current element in subset
let take = subCountRecur(i + 1, sum + arr[i], m, arr, memo);
// Exclude current element
let noTake = subCountRecur(i + 1, sum, m, arr, memo);
// Store and return the result
memo[i][sum] = take + noTake;
return memo[i][sum];
}
// Function which finds Number of
// subsets with sum divisible by m
function subCount(arr, m) {
let n = arr.length;
// Calculate total sum of array
let totalSum = arr.reduce((a, b) => a + b, 0);
// Initialize memoization table with -1
let memo = new Array(n).fill(0).map(() => new Array(totalSum + 1).fill(-1));
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr, memo) - 1;
}
let arr = [1, 2, 3, 4];
let m = 2;
console.log(subCount(arr, m));
Output
7
[Better Approach - 2] Using Bottom-Up DP (Tabulation) – O(sum*n) time and O(sum*n) space
The idea is to fill the DP table based on future values. For each index
iand current sumj, we either includearr[i]or exclude it to compute the number of subsequences whose sum is divisible bym. The table is filled in an iterative manner fromi = n-1down to0, and for each sum from0tototal sum.The dynamic programming relation is as follows:
- dp[i][j] = dp[i+1][j] + dp[i+1][j + arr[i]]
At the base case
i = n, we setdp[n][j] = 1ifj % m == 0, else 0.Finally, subtract 1 from
dp[0][0]to exclude the empty subsequence.
// C++ program to find Number of
// subsets with sum divisible by m
#include <bits/stdc++.h>
using namespace std;
// Function which finds Number of
// subsets with sum divisible by m
int subCount(vector<int> &arr, int m) {
int n = arr.size();
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
vector<vector<int>> dp(n + 1, vector<int>(totalSum + 1, 0));
// Precompute the sums which are divisible
// by m.
for (int j=0; j<=totalSum; j++) {
if (j%m == 0) dp[n][j] = 1;
}
// Current index
for (int i=n-1; i>=0; i--) {
// Current sum
for (int j=0; j<=totalSum; j++) {
dp[i][j] = dp[i+1][j] + dp[i+1][j+arr[i]];
}
}
return dp[0][0] - 1;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
int m = 2;
cout << subCount(arr, m);
return 0;
}
// Java program to find Number of
// subsets with sum divisible by m
import java.util.*;
class Main {
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.length;
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
int[][] dp = new int[n + 1][totalSum + 1];
// Precompute the sums which are divisible
// by m.
for (int j = 0; j <= totalSum; j++) {
if (j % m == 0) dp[n][j] = 1;
}
// Current index
for (int i = n - 1; i >= 0; i--) {
// Current sum
for (int j = 0; j <= totalSum; j++) {
// Exclude arr[i]
dp[i][j] = dp[i + 1][j];
// Include arr[i]
if (j + arr[i] <= totalSum) {
dp[i][j] += dp[i + 1][j + arr[i]];
}
}
}
return dp[0][0] - 1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
System.out.println(subCount(arr, m));
}
}
# Python program to find Number of
# subsets with sum divisible by m
# Function which finds Number of
# subsets with sum divisible by m
def subCount(arr, m):
n = len(arr)
# Calculate total sum of array
totalSum = 0
for num in arr:
totalSum += num
dp = [[0] * (totalSum + 1) for _ in range(n + 1)]
# Precompute the sums which are divisible
# by m.
for j in range(totalSum + 1):
if j % m == 0:
dp[n][j] = 1
# Current index
for i in range(n - 1, -1, -1):
# Current sum
for j in range(totalSum + 1):
# Exclude arr[i]
dp[i][j] = dp[i + 1][j]
# Include arr[i]
if j + arr[i] <= totalSum:
dp[i][j] += dp[i + 1][j + arr[i]]
return dp[0][0] - 1
if __name__ == "__main__":
arr = [1, 2, 3, 4]
m = 2
print(subCount(arr, m))
// C# program to find Number of
// subsets with sum divisible by m
using System;
class GfG {
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.Length;
// Calculate total sum of array
int totalSum = 0;
foreach (int num in arr) {
totalSum += num;
}
int[,] dp = new int[n + 1, totalSum + 1];
// Precompute the sums which are divisible
// by m.
for (int j = 0; j <= totalSum; j++) {
if (j % m == 0) dp[n, j] = 1;
}
// Current index
for (int i = n - 1; i >= 0; i--) {
// Current sum
for (int j = 0; j <= totalSum; j++) {
// Exclude arr[i]
dp[i, j] = dp[i + 1, j];
// Include arr[i]
if (j + arr[i] <= totalSum) {
dp[i, j] += dp[i + 1, j + arr[i]];
}
}
}
return dp[0, 0] - 1;
}
static void Main(string[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
Console.WriteLine(subCount(arr, m));
}
}
// JavaScript program to find Number of
// subsets with sum divisible by m
// Function which finds Number of
// subsets with sum divisible by m
function subCount(arr, m) {
let n = arr.length;
// Calculate total sum of array
let totalSum = 0;
for (let num of arr) {
totalSum += num;
}
let dp = new Array(n + 1).fill(0).map(() => new Array(totalSum + 1).fill(0));
// Precompute the sums which are divisible
// by m.
for (let j = 0; j <= totalSum; j++) {
if (j % m === 0) dp[n][j] = 1;
}
// Current index
for (let i = n - 1; i >= 0; i--) {
// Current sum
for (let j = 0; j <= totalSum; j++) {
// Exclude arr[i]
dp[i][j] = dp[i + 1][j];
// Include arr[i]
if (j + arr[i] <= totalSum) {
dp[i][j] += dp[i + 1][j + arr[i]];
}
}
}
return dp[0][0] - 1;
}
let arr = [1, 2, 3, 4];
let m = 2;
console.log(subCount(arr, m));
Output
7
[Expected Approach - 1] Using Space Optimized DP – O(sum*n) time and O(sum) space
In previous approach of dynamic programming we have derived the relation between states as given below:
- dp[i][j] = dp[i+1][j] + dp[i+1][j + arr[i]]
If we observe carefully, for calculating current
dp[i][j]state we only need values from the next rowdp[i+1][...]. Hence, we can optimize space by using a single 1D array and updating it in reverse to simulate the row transitions.
// C++ program to find Number of
// subsets with sum divisible by m
#include <bits/stdc++.h>
using namespace std;
// Function which finds Number of
// subsets with sum divisible by m
int subCount(vector<int> &arr, int m) {
int n = arr.size();
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
// dp array for tabulation
vector<int> dp(totalSum + 1, 0);
// Base case: sums which are divisible by m
for (int j = 0; j <= totalSum; j++) {
if (j % m == 0) dp[j] = 1;
}
// Process each element in the array
for (int i = n - 1; i >= 0; i--) {
// Current sum
for (int j = 0; j<=totalSum; j++) {
// Include arr[i] if possible
if (j + arr[i] <= totalSum) {
dp[j] += dp[j + arr[i]];
}
}
}
return dp[0] - 1;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
int m = 2;
cout << subCount(arr, m);
return 0;
}
// Java program to find Number of
// subsets with sum divisible by m
import java.util.*;
class GfG {
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.length;
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
// dp array for tabulation
int[] dp = new int[totalSum + 1];
// Base case: sums which are divisible by m
for (int j = 0; j <= totalSum; j++) {
if (j % m == 0) dp[j] = 1;
}
// Process each element in the array
for (int i = n - 1; i >= 0; i--) {
// Current sum
for (int j = 0; j <= totalSum; j++) {
// Include arr[i] if possible
if (j + arr[i] <= totalSum) {
dp[j] += dp[j + arr[i]];
}
}
}
return dp[0] - 1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
System.out.println(subCount(arr, m));
}
}
# Python program to find Number of
# subsets with sum divisible by m
# Function which finds Number of
# subsets with sum divisible by m
def subCount(arr, m):
n = len(arr)
# Calculate total sum of array
totalSum = 0
for num in arr:
totalSum += num
# dp array for tabulation
dp = [0] * (totalSum + 1)
# Base case: sums which are divisible by m
for j in range(totalSum + 1):
if j % m == 0:
dp[j] = 1
# Process each element in the array
for i in range(n - 1, -1, -1):
# Current sum
for j in range(totalSum + 1):
# Include arr[i] if possible
if j + arr[i] <= totalSum:
dp[j] += dp[j + arr[i]]
return dp[0] - 1
if __name__ == "__main__":
arr = [1, 2, 3, 4]
m = 2
print(subCount(arr, m))
// C# program to find Number of
// subsets with sum divisible by m
using System;
class GfG {
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.Length;
// Calculate total sum of array
int totalSum = 0;
foreach (int num in arr) {
totalSum += num;
}
// dp array for tabulation
int[] dp = new int[totalSum + 1];
// Base case: sums which are divisible by m
for (int j = 0; j <= totalSum; j++) {
if (j % m == 0) dp[j] = 1;
}
// Process each element in the array
for (int i = n - 1; i >= 0; i--) {
// Current sum
for (int j = 0; j <= totalSum; j++) {
// Include arr[i] if possible
if (j + arr[i] <= totalSum) {
dp[j] += dp[j + arr[i]];
}
}
}
return dp[0] - 1;
}
static void Main(string[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
Console.WriteLine(subCount(arr, m));
}
}
// JavaScript program to find Number of
// subsets with sum divisible by m
// Function which finds Number of
// subsets with sum divisible by m
function subCount(arr, m) {
let n = arr.length;
// Calculate total sum of array
let totalSum = 0;
for (let num of arr) {
totalSum += num;
}
// dp array for tabulation
let dp = new Array(totalSum + 1).fill(0);
// Base case: sums which are divisible by m
for (let j = 0; j <= totalSum; j++) {
if (j % m === 0) dp[j] = 1;
}
// Process each element in the array
for (let i = n - 1; i >= 0; i--) {
// Current sum
for (let j = 0; j <= totalSum; j++) {
// Include arr[i] if possible
if (j + arr[i] <= totalSum) {
dp[j] += dp[j + arr[i]];
}
}
}
return dp[0] - 1;
}
let arr = [1, 2, 3, 4];
let m = 2;
console.log(subCount(arr, m));
Output
7
[Expected Approach - 2] Further Space Optimization - O(sum*n) time and O(m) space
The idea is to reduce the state space by observing that we only care whether a subsequence sum is divisible by
m, so instead of tracking the exact sum, we can track the remainder of the sum modulom. We definedp[i][curr]as the number of subsequences starting from indexiwith a current sum having remaindercurrmodulom. The recurrence becomesdp[i][curr] = dp[i + 1][(curr + arr[i]) % m] + dp[i + 1][curr], representing the choices to include or excludearr[i]. This allows us to reduce the DP table size from O(n × sum) to O(n × m), optimizing both time and space.
Refer to Number of subsets with sum divisible by M | Set 2 for detailed explanation and code.
Related Articles: