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
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