Subsequences of size three in an array whose sum is divisible by m
Last Updated :
28 Mar, 2023
Given an array A[] (1<=A_i <=10^9 ) of size N (1<=N<=10^5 ), find the number of subsequences of length 3 whose sum is divisible by M (1<=M<=10^3 ).
Examples:
Input : A[] = {1, 2, 4, 3}
M = 3
Output : 2
Explanation : We can choose two such
subsequence of length 3 such that its
sum is divisible by 3 -> {1, 2, 3} ans
{2, 4, 3}
Brute Force Approach: We use 3 nested loops to traverse all the subsequences of length 3 to count all such subsequence which satisfies the given condition.
Here the brute force solution will work in O(N^3 )
Implementation:
C++
// Brute Force Implementation (Time Complexity :
// O(N^3)) C++ program to find count of subsequences of size
// three divisible by M.
#include <bits/stdc++.h>
using namespace std;
int coutSubSeq(int A[], int N, int M)
{
int sum = 0;
int ans = 0;
// Three nested loop to find all the sub
// sequences of length three in the given
// array A[].
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
for (int k = j + 1; k < N; k++) {
sum = A[i] + A[j] + A[k];
// checking if the sum of the chosen
// three number is divisible by m.
if (sum % M == 0)
ans++;
}
}
}
return ans;
}
// Driver code
int main()
{
int M = 3;
int A[] = { 1, 2, 4, 3 };
int N = sizeof(A)/sizeof(A[0]);
cout << coutSubSeq(A, N, M);
return 0;
}
Java
// Java program to find count of
// subsequences of size three
// divisible by M.
import java.io.*;
class GFG {
static int coutSubSeq(int A[], int N,
int M)
{
int sum = 0;
int ans = 0;
// Three nested loop to find all the
// sub sequences of length three in
// the given array A[].
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
for (int k = j + 1; k < N; k++) {
sum = A[i] + A[j] + A[k];
// checking if the sum of the
// chosen three number is
// divisible by m.
if (sum % M == 0)
ans++;
}
}
}
return ans;
}
// Driver code
public static void main(String args[])
{
int M = 3;
int A[] = { 1, 2, 4, 3 };
int N = A.length;
System.out.println(coutSubSeq(A, N, M));
}
}
/*This code is contributed by Nikita Tiwari*/
Python
# Python program to find count of
# subsequences of size three
# divisible by M.
def coutSubSeq(A, N,M) :
sum = 0
ans = 0
# Three nested loop to find all the
# sub sequences of length three in
# the given array A[].
for i in range(0, N) :
for j in range(i + 1, N) :
for k in range(j + 1, N) :
sum = A[i] + A[j] + A[k]
# checking if the sum of
# the chosen three number
# is divisible by m.
if (sum % M == 0) :
ans = ans + 1
return ans
# Driver code
M = 3
A = [ 1, 2, 4, 3 ]
N = len(A)
print coutSubSeq(A, N, M)
# This code is contributed by Nikita Tiwari.
C#
// C# program to find count of subsequences
// of size three divisible by M.
using System;
class GFG {
static int coutSubSeq(int[] A, int N, int M)
{
int sum = 0;
int ans = 0;
// Three nested loop to find all the
// sub sequences of length three in
// the given array A[].
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
for (int k = j + 1; k < N; k++)
{
sum = A[i] + A[j] + A[k];
// checking if the sum of
// the chosen three number
// is divisible by m.
if (sum % M == 0)
ans++;
}
}
}
return ans;
}
// Driver code
public static void Main()
{
int M = 3;
int []A = { 1, 2, 4, 3 };
int N = A.Length;
Console.WriteLine(coutSubSeq(A, N, M));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// Brute Force Implementation (Time Complexity :
// O(N^3)) PHP program to find count of subsequences of size
// three divisible by M.
function coutSubSeq($A, $N, $M)
{
$sum = 0;
$ans = 0;
// Three nested loop to find all the sub
// sequences of length three in the given
// array A[].
for ( $i = 0; $i <$N; $i++) {
for ( $j = $i + 1; $j < $N; $j++) {
for ( $k = $j + 1; $k < $N; $k++) {
$sum = $A[$i] + $A[$j] + $A[$k];
// checking if the sum of the
// chosen three number is
// divisible by m.
if ($sum % $M == 0)
$ans++;
}
}
}
return $ans;
}
// Driver code
$M = 3;
$A = array( 1, 2, 4, 3 );
$N = count($A);
echo coutSubSeq($A, $N, $M);
// This code is contributed by anuj_67.
?>
JavaScript
<script>
// Javascript program to find count of
// subsequences of size three
// divisible by M.
function coutSubSeq(A, N, M)
{
let sum = 0;
let ans = 0;
// Three nested loop to find all the
// sub sequences of length three in
// the given array A[].
for (let i = 0; i < N; i++) {
for (let j = i + 1; j < N; j++) {
for (let k = j + 1; k < N; k++) {
sum = A[i] + A[j] + A[k];
// checking if the sum of the
// chosen three number is
// divisible by m.
if (sum % M == 0)
ans++;
}
}
}
return ans;
}
// Driver code
let M = 3;
let A = [ 1, 2, 4, 3 ];
let N = A.length;
document.write(coutSubSeq(A, N, M));
</script>
Second Approach (Efficient for small M):
The above implementation takes a lot of time. So we need a better approach to solve this. Here we will use index mapping (hashing technique) to solve the problem. As we need to check if the sum of the chosen three numbers is divisible by M, we store each value under modulo M. We use a frequency array to store the number of occurrences of each element using index mapping techniques.
Three cases may occur:
- Firstly, if thrice of a number is divisible by M then we will add {{N}\choose{3}} to answer where N is frequency of that number.
- Secondly, if twice of some number A added with sum number B is divisible by M then we will add {{Freq[A]}\choose{2}} * Freq[B] to the answer.
- Thirdly, if all the numbers A, B, C that sum up to S which is divisible by M then we will add Freq[A] * Freq[B] * Freq[C] to the answer.
With this approach, we can solve the problem in O(M^2 ) which is executable in the given time.
Implementation:
C++
// O(M^2) time complexity C++ program to find
// count of subsequences of size three
// divisible by M.
#include <iostream>
using namespace std;
int countSubSeq(int A[], int N, int M)
{
int ans = 0;
// Storing frequencies of all remainders
// when divided by M.
int h[M] = { 0 };
for (int i = 0; i < N; i++) {
A[i] = A[i] % M;
h[A[i]]++;
}
for (int i = 0; i < M; i++) {
for (int j = i; j < M; j++) {
// including i and j in the sum rem
// calculate the remainder required
// to make the sum divisible by M
int rem = (M - (i + j) % M) % M;
// if the required number is less than
// j, we skip as we have already calculated
// for that value before. As j here starts
// with i and rem is less than j.
if (rem < j)
continue;
// if satisfies the first case.
if (i == j && rem == j)
ans += h[i] * (h[i] - 1) * (h[i] - 2) / 6;
// if satisfies the second case
else if (i == j)
ans += h[i] * (h[i] - 1) * h[rem] / 2;
else if (i == rem)
ans += h[i] * (h[i] - 1) * h[j] / 2;
else if (rem == j)
ans += h[j] * (h[j] - 1) * h[i] / 2;
// if satisfies the third case
else
ans = ans + h[i] * h[j] * h[rem];
}
}
return ans;
}
// Driver code
int main()
{
int M = 3;
int A[] = { 1, 2, 4, 3 };
int N = sizeof(A)/sizeof(A[0]);
cout << countSubSeq(A, N, M);
return 0;
}
Java
// Java program to find count of
// subsequences of size three
// divisible by M.
import java.io.*;
import java.util.Arrays;
class GFG {
static int countSubSeq(int A[], int N, int M)
{
int ans = 0;
// Storing frequencies of all
// remainders when divided by M.
int h[] = new int[M];
Arrays.fill(h,0);
for (int i = 0; i < N; i++) {
A[i] = A[i] % M;
h[A[i]]++;
}
for (int i = 0; i < M; i++) {
for (int j = i; j < M; j++) {
// including i and j in the sum
// rem calculate the remainder
// required to make the sum
// divisible by M
int rem = (M - (i + j) % M) % M;
// if the required number is
// less than j, we skip as we
// have already calculated for
// that value before. As j here
// starts with i and rem is
// less than j.
if (rem < j)
continue;
// if satisfies the first case.
if (i == j && rem == j)
ans += h[i] * (h[i] - 1) *
(h[i] - 2) / 6;
// if satisfies the second case
else if (i == j)
ans += h[i] * (h[i] - 1) *
h[rem] / 2;
else if (i == rem)
ans += h[i] * (h[i] - 1) *
h[j] / 2;
else if (rem == j)
ans += h[j] * (h[j] - 1) *
h[i] / 2;
// if satisfies the third case
else
ans = ans + h[i] * h[j] *
h[rem];
}
}
return ans;
}
// Driver code
public static void main(String args[])
{
int M = 3;
int A[] = { 1, 2, 4, 3 };
int N = A.length;
System.out.println(countSubSeq(A, N, M));
}
}
/*This code is contributed by Nikita Tiwari*/
Python
# Python program to find count of
# subsequences of size three
# divisible by M.
def countSubSeq(A, N, M) :
ans = 0
# Storing frequencies of all
# remainders when divided by M.
h = [0] * M
for i in range(0,N) :
A[i] = A[i] % M
h[A[i]] = h[A[i]] + 1
for i in range(0,M) :
for j in range(i,M) :
# including i and j in the sum
# rem calculate the remainder
# required to make the sum
# divisible by M
rem = (M - (i + j) % M) % M
# if the required number is
# less than j, we skip as we
# have already calculated for
# that value before. As j here
# starts with i and rem is
# less than j.
if (rem < j) :
continue
# if satisfies the first case.
if (i == j and rem == j) :
ans = ans + h[i] * (h[i] - 1) * (h[i] - 2) / 6
# if satisfies the second case
elif (i == j) :
ans = ans +( h[i] * (h[i] - 1) * h[rem] / 2)
elif (i == rem) :
ans = ans + h[i] * (h[i] - 1) * h[j] / 2
elif (rem == j) :
ans = ans + h[j] * (h[j] - 1) * h[i] / 2
# if satisfies the third case
else :
ans = ans + h[i] * h[j] * h[rem]
return ans
# Driver code
M = 3;
A = [ 1, 2, 4, 3 ]
N = len(A)
print(countSubSeq(A, N, M))
# This code is contributed by Nikita Tiwari.
C#
// C# program to find count of subsequences of
// size three divisible by M.
using System;
class GFG {
static int countSubSeq(int []A, int N, int M)
{
int ans = 0;
// Storing frequencies of all
// remainders when divided by M.
int []h = new int[M];
for (int i = 0; i < N; i++) {
A[i] = A[i] % M;
h[A[i]]++;
}
for (int i = 0; i < M; i++) {
for (int j = i; j < M; j++) {
// including i and j in the sum
// rem calculate the remainder
// required to make the sum
// divisible by M
int rem = (M - (i + j) % M) % M;
// if the required number is
// less than j, we skip as we
// have already calculated for
// that value before. As j here
// starts with i and rem is
// less than j.
if (rem < j)
continue;
// if satisfies the first case.
if (i == j && rem == j)
ans += h[i] * (h[i] - 1) *
(h[i] - 2) / 6;
// if satisfies the second case
else if (i == j)
ans += h[i] * (h[i] - 1) *
h[rem] / 2;
else if (i == rem)
ans += h[i] * (h[i] - 1) *
h[j] / 2;
else if (rem == j)
ans += h[j] * (h[j] - 1) *
h[i] / 2;
// if satisfies the third case
else
ans = ans + h[i] * h[j] *
h[rem];
}
}
return ans;
}
// Driver code
public static void Main()
{
int M = 3;
int []A = { 1, 2, 4, 3 };
int N = A.Length;
Console.WriteLine(countSubSeq(A, N, M));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// O(M^2) time complexity PHP program to find
// count of subsequences of size three
// divisible by M.
function countSubSeq($A, $N, $M)
{
$ans = 0;
// Storing frequencies of all remainders
// when divided by M.
$h = array_fill(0, $M, 0);
for ($i = 0; $i < $N; $i++)
{
$A[$i] = $A[$i] % $M;
$h[$A[$i]]++;
}
for ($i = 0; $i < $M; $i++)
{
for ($j = $i; $j < $M; $j++)
{
// including i and j in the sum rem
// calculate the remainder required
// to make the sum divisible by M
$rem = ($M - ($i + $j) % $M) % $M;
// if the required number is less than
// j, we skip as we have already calculated
// for that value before. As j here starts
// with i and rem is less than j.
if ($rem < $j)
continue;
// if satisfies the first case.
if ($i == $j && $rem == $j)
$ans += $h[$i] * ($h[$i] - 1) *
($h[$i] - 2) / 6;
// if satisfies the second case
else if ($i == $j)
$ans += $h[$i] * ($h[$i] - 1) *
$h[$rem] / 2;
else if ($i == $rem)
$ans += $h[$i] * ($h[$i] - 1) *
$h[$j] / 2;
else if ($rem == $j)
$ans += $h[$j] * ($h[$j] - 1) *
$h[$i] / 2;
// if satisfies the third case
else
$ans = $ans + $h[$i] *
$h[$j] * $h[$rem];
}
}
return $ans;
}
// Driver code
$M = 3;
$A = array( 1, 2, 4, 3 );
$N = count($A);
echo countSubSeq($A, $N, $M);
// This code is contributed by mits
?>
JavaScript
<script>
// javascript program to find count of
// subsequences of size three
// divisible by M.
function countSubSeq(A , N , M)
{
var ans = 0;
// Storing frequencies of all
// remainders when divided by M.
var h = Array.from({length: M}, (_, i) => 0);
for (var i = 0; i < N; i++) {
A[i] = A[i] % M;
h[A[i]]++;
}
for (var i = 0; i < M; i++) {
for (var j = i; j < M; j++) {
// including i and j in the sum
// rem calculate the remainder
// required to make the sum
// divisible by M
var rem = (M - (i + j) % M) % M;
// if the required number is
// less than j, we skip as we
// have already calculated for
// that value before. As j here
// starts with i and rem is
// less than j.
if (rem < j)
continue;
// if satisfies the first case.
if (i == j && rem == j)
ans += h[i] * (h[i] - 1) *
(h[i] - 2) / 6;
// if satisfies the second case
else if (i == j)
ans += h[i] * (h[i] - 1) *
h[rem] / 2;
else if (i == rem)
ans += h[i] * (h[i] - 1) *
h[j] / 2;
else if (rem == j)
ans += h[j] * (h[j] - 1) *
h[i] / 2;
// if satisfies the third case
else
ans = ans + h[i] * h[j] *
h[rem];
}
}
return ans;
}
// Driver code
var M = 3;
var A = [ 1, 2, 4, 3 ];
var N = A.length;
document.write(countSubSeq(A, N, M));
// This code contributed by Princi Singh
</script>
complexity analysis:
The time complexity of the given program is O(M^2) as it has two nested loops iterating over the range [0, M).
The space complexity is O(M) as an array of size M is created to store the frequencies of remainders when divided by M.
Similar Reads
Find a subarray whose sum is divisible by size of the array
Given an array arr[] of length N. The task is to check if there exists any subarray whose sum is a multiple of N. If there exists such subarray, then print the starting and ending index of that subarray else print -1. If there are multiple such subarrays, print any of them. Examples: Input: arr[] =
13 min read
Longest subsequence whose sum is divisible by a given number
Given an array arr[] and an integer M, the task is to find the length of the longest subsequence whose sum is divisible by M. If there is no such sub-sequence then print 0. Examples: Input: arr[] = {3, 2, 2, 1}, M = 3 Output: 3 Longest sub-sequence whose sum is divisible by 3 is {3, 2, 1}Input: arr[
15+ min read
Number of subsequences in a string divisible by n
Given a string consisting of digits 0-9, count the number of subsequences in it divisible by m.Examples: Input : str = "1234", n = 4Output : 4The subsequences 4, 12, 24 and 124 are divisible by 4. Input : str = "330", n = 6Output : 4The subsequences 30, 30, 330 and 0 are divisible by n.Input : str =
11 min read
Maximize the numbers of splits in an Array having sum divisible by 3
Given an integer array arr of size N. The task is to find the maximum number of splits such that each split has sum divisible by 3. It is not necessary that all splits are divisible by 3, the task is to just maximize the number of splits which are divisible by 3.Examples: Input: arr [] = [2, 36, 1,
7 min read
Count of subsequences in an array with sum less than or equal to X
Given an integer array arr[] of size N and an integer X, the task is to count the number of subsequences in that array such that its sum is less than or equal to X. Note: 1 <= N <= 1000 and 1 <= X <= 1000, where N is the size of the array. Examples: Input : arr[] = {84, 87, 73}, X = 100
13 min read
Maximizing the sum of subsequence of size at most M
Given array A[] of size N, integer M and integer K. The task is to choose at most M elements from the array A[] to form a new array such that if the previous element was chosen is at index i that is A[i] and the current element at index j that is A[j] append A[j] - K * (j - i) to new array. Find the
9 min read
Find the maximum range [L,R] whose sum is divisible by M
Given an array arr[] consisting of positive numbers, the task is to find the maximum range [L, R] whose sum is divisible by M. If there is no range present return -1. Examples: Input: arr[] = {3, 7, 5, 2, 5, 10}, M = 3 Output: 1 3 Explanation: Sum of numbers from 1 to 3 is 3+7+5 which is 15. Input :
8 min read
Find the count of subsequences where each element is divisible by K
Given an array arr[] and an integer K, the task is to find the total number of subsequences from the array where each element is divisible by K.Examples: Input: arr[] = {1, 2, 3, 6}, K = 3 Output: 3 {3}, {6} and {3, 6} are the only valid subsequences.Input: arr[] = {5, 10, 15, 20, 25}, K = 5 Output:
4 min read
Longest sub-sequence of a binary string divisible by 3
Given a binary string S of length N, the task is to find the length of the longest sub-sequence in it which is divisible by 3. Leading zeros in the sub-sequences are allowed.Examples:  Input: S = "1001" Output: 4 The longest sub-sequence divisible by 3 is "1001". 1001 = 9 which is divisible by 3.In
9 min read
Number of subsets with sum divisible by M | Set 2
Given an array arr[] of N integers 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. Examples: Input: arr[] = {1, 2, 3}, M = 1 Output: 7 Number of non-empty subsets of this array are 7. Since m = 1, m will divide all th
15+ min read