Count pairs in an array whose absolute difference is divisible by K
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++
#include <bits/stdc++.h>
using namespace std;
void countPairs( int arr[], int n, int k)
{
int i, j, cnt = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if ( abs (arr[i] - arr[j]) % k == 0)
cnt += 1;
}
}
cout << cnt << endl;
}
int main()
{
int arr[] = {3, 3, 3};
int k = 3;
int n = sizeof (arr) / sizeof (arr[0]);
countPairs(arr, n, k);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void countPairs( int arr[], int n, int k)
{
int i, j, cnt = 0 ;
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" );
}
public static void main(String[] args)
{
int arr[] = { 3 , 3 , 3 };
int k = 3 ;
int n = arr.length;
countPairs(arr, n, k);
}
}
|
Python3
def countPairs(arr, n, k) :
cnt = 0 ;
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) ;
if __name__ = = "__main__" :
arr = [ 3 , 3 , 3 ];
k = 3 ;
n = len (arr);
countPairs(arr, n, k);
|
C#
using System;
class GFG
{
static void countPairs( int []arr, int n, int k)
{
int i, j, cnt = 0;
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" );
}
public static void Main(String[] args)
{
int []arr = {3, 3, 3};
int k = 3;
int n = arr.Length;
countPairs(arr, n, k);
}
}
|
Javascript
<script>
function countPairs(arr, n, k)
{
var i, j, cnt = 0;
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" );
}
var arr = [ 3, 3, 3 ];
var k = 3;
var n = arr.length;
countPairs(arr, n, k);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach:
Algorithm:
- Convert each elements (A[i]) of the array to ((A[i]+K)%K)
- Use hashing technique to store the number of times (A[i]%K) occurs in the array
- Now, if an element H[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
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void countPair( int arr[], int n, int k)
{
int cnt = 0;
for ( int i = 0; i < n; i++) {
arr[i] = (arr[i] + k) % k;
}
int hash[k] = { 0 };
for ( int i = 0; i < n; i++) {
hash[arr[i]]++;
}
for ( int i = 0; i < k; i++) {
cnt += (hash[i] * (hash[i] - 1)) / 2;
}
cout << cnt << endl;
}
int main()
{
int arr[] = {1, 2, 3, 4};
int k = 2;
int n = sizeof (arr) / sizeof (arr[0]);
countPair(arr, n, k);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void countPair( int arr[], int n, int k)
{
int cnt = 0 ;
for ( int i = 0 ; i < n; i++)
{
arr[i] = (arr[i] + k) % k;
}
int hash[] = new int [k];
for ( int i = 0 ; i < n; i++)
{
hash[arr[i]]++;
}
for ( int i = 0 ; i < k; i++)
{
cnt += (hash[i] * (hash[i] - 1 )) / 2 ;
}
System.out.print(cnt + "\n" );
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 };
int k = 2 ;
int n = arr.length;
countPair(arr, n, k);
}
}
|
Python3
def countPair(arr, n, k):
cnt = 0 ;
for i in range (n):
arr[i] = (arr[i] + k) % k;
hash = [ 0 ] * k;
for i in range (n):
hash [arr[i]] + = 1 ;
for i in range (k):
cnt + = ( hash [i] * ( hash [i] - 1 )) / 2 ;
print ( int (cnt));
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 4 ];
k = 2 ;
n = len (arr);
countPair(arr, n, k);
|
C#
using System;
class GFG
{
static void countPair( int []arr, int n, int k)
{
int cnt = 0;
for ( int i = 0; i < n; i++)
{
arr[i] = (arr[i] + k) % k;
}
int []hash = new int [k];
for ( int i = 0; i < n; i++)
{
hash[arr[i]]++;
}
for ( int i = 0; i < k; i++)
{
cnt += (hash[i] * (hash[i] - 1)) / 2;
}
Console.Write(cnt + "\n" );
}
public static void Main(String[] args)
{
int []arr = {1, 2, 3, 4};
int k = 2;
int n = arr.Length;
countPair(arr, n, k);
}
}
|
Javascript
<script>
function countPair(arr, n, k)
{
let cnt = 0;
for (let i = 0; i < n; i++)
{
arr[i] = (arr[i] + k) % k;
}
let hash = Array.from({length: k}, (_, i) => 0);
for (let i = 0; i < n; i++)
{
hash[arr[i]]++;
}
for (let i = 0; i < k; i++)
{
cnt += (hash[i] * (hash[i] - 1)) / 2;
}
document.write(cnt + "<br/>" );
}
let arr = [1, 2, 3, 4];
let k = 2;
let n = arr.length;
countPair(arr, n, k);
</script>
|
Time Complexity: O(n+k)
Auxiliary Space: O(k)
Using unordered map approach:
Suppose we have two numbers x1 and x2 and we want (x1 -x2) to be divisible by k
and we know that if both numbers are divisible by k then if we subtract them they will also be divisible by k
for example K=2 (4-2) is divisible by 2 because ( 4 is divisible by 2 ) and ( 2 is also divisible by 2 ).
so what x%k give us ?? it give us if we add x%k or subtract x%k from that number it will became divisible by k
for example: k=5 and x=2 (5%2) = 1 if we add 1 to 5 it will became 6 which is divisible by 2 and if we subtract 1 from 5 it will became 4 which is also divisible by 2. so what we will do we will check and can i get arr[i]%k from any previous number so that i will add arr[i]%k to my current number and subtract arr[i]%k to my previous number to make both the numbers divisible by k .
for example: [5,7] K=2
5%2 = 1 // subtract one to make it divisible by K
7%2 =1 // needs one to make it divisible by K
or vice versa we will take one from 5 to make it divisible by K
Implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
void countPair( int arr[], int n, int k)
{
unordered_map< int , int > map;
int res = 0;
for ( int i = 0; i < n; ++i) {
if (map.find(arr[i] % k) != map.end()) {
res += map[arr[i] % k];
}
map[arr[i] % k]++;
}
cout << res;
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int k = 2;
int n = sizeof (arr) / sizeof (arr[0]);
countPair(arr, n, k);
return 0;
}
|
Java
import java.util.*;
class Main {
static void countPair( int [] arr, int n, int k)
{
Map<Integer, Integer> map = new HashMap<>();
int res = 0 ;
for ( int i = 0 ; i < n; ++i) {
if (map.containsKey(arr[i] % k)) {
res += map.get(arr[i] % k);
}
map.put(arr[i] % k,
map.getOrDefault(arr[i] % k, 0 ) + 1 );
}
System.out.println(res);
}
public static void main(String[] args)
{
int [] arr = { 1 , 2 , 3 , 4 };
int k = 2 ;
int n = arr.length;
countPair(arr, n, k);
}
}
|
Python3
def countPair(arr, n, k):
dict = {}
res = 0
for i in range (n):
if arr[i] % k in dict :
res + = dict [arr[i] % k]
dict [arr[i] % k] = dict .get(arr[i] % k, 0 ) + 1
print (res)
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 4 ]
k = 2
n = len (arr)
countPair(arr, n, k)
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static void countPair( int [] arr, int n, int k)
{
Dictionary< int , int > map = new Dictionary< int , int >();
int res = 0;
for ( int i = 0; i < n; ++i)
{
if (map.ContainsKey(arr[i] % k))
{
res += map[arr[i] % k];
}
if (map.ContainsKey(arr[i] % k))
{
map[arr[i] % k]++;
}
else
{
map.Add(arr[i] % k, 1);
}
}
Console.WriteLine(res);
}
static void Main()
{
int [] arr = { 1, 2, 3, 4 };
int k = 2;
int n = arr.Length;
countPair(arr, n, k);
}
}
|
Javascript
function countPair(arr, n, k) {
let dict = {};
let res = 0;
for (let i = 0; i < n; i++) {
if (arr[i] % k in dict) {
res += dict[arr[i] % k];
}
dict[arr[i] % k] = (dict[arr[i] % k] || 0) + 1;
}
console.log(res);
}
let arr = [1, 2, 3, 4];
let k = 2;
let n = arr.length;
countPair(arr, n, k);
|
Time Complexity: O(n)
Auxiliary Space: O(k)
This approach is contributed by Prateek Kumar Singh (pkrsingh025).
Last Updated :
17 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...