Count pairs in an array whose absolute difference is divisible by K - GeeksforGeeks

24 Feb, 2022
Given an array arr[] and a positive integer K. The task is to count the total number of pairs in the array whose absolute difference is divisible by K. 
Examples: 
Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 2 Explanation: Total 2 pairs exists in the array with absolute difference divisible by 2. The pairs are: (1, 3), (2, 4).
Input: arr[] = {3, 3, 3}, K = 3 Output: 3 Explanation: Total 3 pairs exists in this array with absolute difference divisible by 3. The pairs are: (3, 3), (3, 3), (3, 3).  
Naive Approach: The idea is to check for each pair of the array one by one and count the total number pairs whose absolute difference is divisible by K.  
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // function to count pairs in an array// whose absolute difference is// divisible by kvoid countPairs(int arr[], int n, int k){     // initialize count as zero.    int i, j, cnt = 0;     // loop to count the valid pair    for (i = 0; i < n - 1; i++) {        for (j = i + 1; j < n; j++) {            if ((arr[i] - arr[j] + k) % k == 0)                cnt += 1;        }    }    cout << cnt << endl;} // Driver codeint main(){    // input array    int arr[] = {3, 3, 3};    int k = 3;     // calculate the size of array    int n = sizeof(arr) / sizeof(arr[0]);     // function to count the valid pair    countPairs(arr, n, k);    return 0;}
import java.util.*; class GFG{ // function to count pairs in an array// whose absolute difference is// divisible by kstatic void countPairs(int arr[], int n, int k){     // initialize count as zero.    int i, j, cnt = 0;     // loop to count the valid pair    for (i = 0; i < n - 1; i++)    {        for (j = i + 1; j < n; j++)        {            if ((arr[i] - arr[j] + k) % k == 0)                cnt += 1;        }    }    System.out.print(cnt +"\n");} // Driver codepublic static void main(String[] args){    // input array    int arr[] = {3, 3, 3};    int k = 3;     // calculate the size of array    int n = arr.length;     // function to count the valid pair    countPairs(arr, n, k);}} // This code is contributed by 29AjayKumar
# Python3 Code implementation of the above approach # function to count pairs in an array# whose absolute difference is# divisible by kdef countPairs(arr, n, k) :     # initialize count as zero.    cnt = 0;     # loop to count the valid pair    for i in range(n - 1) :        for j in range(i + 1, n) :            if ((arr[i] - arr[j] + k) % k == 0) :                cnt += 1;         print(cnt) ; # Driver codeif __name__ == "__main__" :     # input array    arr = [3, 3, 3];    k = 3;     # calculate the size of array    n = len(arr);     # function to count the valid pair    countPairs(arr, n, k);     # This code is contributed by AnkitRai01
using System; class GFG{ // function to count pairs in an array// whose absolute difference is// divisible by kstatic void countPairs(int []arr, int n, int k){     // initialize count as zero.    int i, j, cnt = 0;     // loop to count the valid pair    for (i = 0; i < n - 1; i++)    {        for (j = i + 1; j < n; j++)        {            if ((arr[i] - arr[j] + k) % k == 0)                cnt += 1;        }    }    Console.Write(cnt +"\n");} // Driver codepublic static void Main(String[] args){    // input array    int []arr = {3, 3, 3};    int k = 3;     // calculate the size of array    int n = arr.Length;     // function to count the valid pair    countPairs(arr, n, k);}} // This code is contributed by 29AjayKumar
<script> // Function to count pairs in an array// whose absolute difference is// divisible by kfunction countPairs(arr, n, k){         // Initialize count as zero.    var i, j, cnt = 0;     // Loop to count the valid pair    for(i = 0; i < n - 1; i++)    {        for(j = i + 1; j < n; j++)        {            if ((arr[i] - arr[j] + k) % k == 0)                cnt += 1;        }    }    document.write(cnt + "\n");} // Driver code // Input arrayvar arr = [ 3, 3, 3 ];var k = 3; // Calculate the size of arrayvar n = arr.length; // Function to count the valid paircountPairs(arr, n, k); // This code is contributed by umadevi9616 </script>
3
 
Time Complexity: O(N2) Space Complexity:O(1)
Efficient Approach:  
Algorithm:  
Convert each elements (A[i]) of the array to ((A[i]+K)%K)Use hashing teching technique to store the number of times (A[i]%K) occurs in the arrayNow, if an element A[i] occurs x times in the array then add x*(x-1)/2 (choosing any 2 elements out of x elements ) in the count pair where 1<=i<=n .This is because value of each elements of the array lies between 0 to K-1 so the absolute difference is divisible only if value of both the elements of a pair are equal
Convert each elements (A[i]) of the array to ((A[i]+K)%K)
Use hashing teching technique to store the number of times (A[i]%K) occurs in the array
Now, if an element A[i] occurs x times in the array then add x*(x-1)/2 (choosing any 2 elements out of x elements ) in the count pair where 1<=i<=n .This is because value of each elements of the array lies between 0 to K-1 so the absolute difference is divisible only if value of both the elements of a pair are equal
C++
Java
Python3
C#
Javascript
// Write CPP code here#include <bits/stdc++.h>using namespace std; // function to Count pairs in an array whose// absolute difference is divisible by kvoid countPair(int arr[], int n, int k){     // initialize the count    int cnt = 0;     // making every element of arr in    // range 0 to k - 1    for (int i = 0; i < n; i++) {        arr[i] = (arr[i] + k) % k;    }     // create an array hash[]    int hash[k] = { 0 };     // store to count of element of arr    // in hash[]    for (int i = 0; i < n; i++) {        hash[arr[i]]++;    }     // count the pair whose absolute    // difference is divisible by k    for (int i = 0; i < k; i++) {        cnt += (hash[i] * (hash[i] - 1)) / 2;    }     // print the value of count    cout << cnt << endl;} // Driver Codeint main(){    // input array    int arr[] = {1, 2, 3, 4};    int k = 2;     // calculate the size of array    int n = sizeof(arr) / sizeof(arr[0]);    countPair(arr, n, k);    return 0;}
// JAVA Implementation of above approachimport java.util.*; class GFG{ // function to Count pairs in an array whose// absolute difference is divisible by kstatic void countPair(int arr[], int n, int k){     // initialize the count    int cnt = 0;     // making every element of arr in    // range 0 to k - 1    for (int i = 0; i < n; i++)    {        arr[i] = (arr[i] + k) % k;    }     // create an array hash[]    int hash[] = new int[k];     // store to count of element of arr    // in hash[]    for (int i = 0; i < n; i++)    {        hash[arr[i]]++;    }     // count the pair whose absolute    // difference is divisible by k    for (int i = 0; i < k; i++)    {        cnt += (hash[i] * (hash[i] - 1)) / 2;    }     // print the value of count    System.out.print(cnt +"\n");} // Driver Codepublic static void main(String[] args){    // input array    int arr[] = {1, 2, 3, 4};    int k = 2;     // calculate the size of array    int n = arr.length;    countPair(arr, n, k);}} // This code is contributed by PrinciRaj1992
# Python3 Implementation of above approach # function to Count pairs in an array whose# absolute difference is divisible by kdef countPair(arr, n, k):     # initialize the count    cnt = 0;     # making every element of arr in    # range 0 to k - 1    for i in range(n):        arr[i] = (arr[i] + k) % k;     # create an array hash    hash = [0]*k;     # store to count of element of arr    # in hash    for i in range(n):        hash[arr[i]] += 1;     # count the pair whose absolute    # difference is divisible by k    for i in range(k):        cnt += (hash[i] * (hash[i] - 1)) / 2;     # print value of count    print(int(cnt)); # Driver Codeif __name__ == '__main__':     # input array    arr = [1, 2, 3, 4];    k = 2;     # calculate the size of array    n = len(arr);    countPair(arr, n, k); # This code is contributed by 29AjayKumar
// C# Implementation of above approachusing System; class GFG{ // function to Count pairs in an array whose// absolute difference is divisible by kstatic void countPair(int []arr, int n, int k){     // initialize the count    int cnt = 0;     // making every element of arr in    // range 0 to k - 1    for (int i = 0; i < n; i++)    {        arr[i] = (arr[i] + k) % k;    }     // create an array hash[]    int []hash = new int[k];     // store to count of element of arr    // in hash[]    for (int i = 0; i < n; i++)    {        hash[arr[i]]++;    }     // count the pair whose absolute    // difference is divisible by k    for (int i = 0; i < k; i++)    {        cnt += (hash[i] * (hash[i] - 1)) / 2;    }     // print the value of count    Console.Write(cnt +"\n");} // Driver Codepublic static void Main(String[] args){    // input array    int []arr = {1, 2, 3, 4};    int k = 2;     // calculate the size of array    int n = arr.Length;    countPair(arr, n, k);}} // This code is contributed by 29AjayKumar
<script> // Javascript Implementation of above approach // function to Count pairs in an array whose// absolute difference is divisible by kfunction countPair(arr, n, k){    // let initialize the count    let cnt = 0;      // making every element of arr in    // range 0 to k - 1    for (let i = 0; i < n; i++)    {        arr[i] = (arr[i] + k) % k;    }      // create an array hash[]    let hash =  Array.from({length: k}, (_, i) => 0);      // store to count of element of arr    // in hash[]    for (let i = 0; i < n; i++)    {        hash[arr[i]]++;    }      // count the pair whose absolute    // difference is divisible by k    for (let i = 0; i < k; i++)    {        cnt += (hash[i] * (hash[i] - 1)) / 2;    }      // print the value of count    document.write(cnt +"<br/>");}       // Driver code           // input array    let arr = [1, 2, 3, 4];    let k = 2;      // calculate the size of array    let n = arr.length;    countPair(arr, n, k);                                                                                      </script>
2
 
Time Complexity: O(n+k) Auxiliary Space: O(k) 
29AjayKumar
princiraj1992
ankthon
umadevi9616
susmitakundugoaldanga
arorakashish0911
simmytarika5
khushboogoyal499
simranarora5sos
Technical Scripter 2019
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)