Count pairs in an array whose absolute difference is divisible by K | Using Map
Given an array, arr[] of N elements and an integer K, the task is to find the number of pairs (i, j) such that the absolute value of (arr[i] – arr[j]) is a multiple of K.
Examples:
Input: N = 4, K = 2, arr[] = {1, 2, 3, 4}
Output: 2
Explanation: Total 2 pairs exists in the array with absolute difference divisible by 2. The pairs are: (1, 3), (2, 4).
Input: N = 3, K = 3, arr[] = {3, 3, 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 easiest way is to iterate through every possible pair in the array and if the absolute difference of the numbers is a multiple of K, then increase the count by 1. Print the value of the count after all pairs are processed.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Frequency Array Approach: The approach to solving this problem using a frequency array is discussed in Set-1 of this article. In this approach, we have discussed the approach to solve it using the map.
Efficient Approach: To optimize the above approach, the idea is to observe the fact that for two numbers a[i] and a[j], if a[i] % k = a[j] % k, then abs(a[i] – a[j]) is a multiple of K. Follow the below steps to solve the problem:
- Initialize the variable ans as 0 to store the answer.
- Declare an unordered_map<int, int> count_map[] which stores the count of remainders of array elements with K.
- Iterate over the range [1, N] using the variable index and increment the value arr[index]%k in the count_map by 1 for every index.
- Iterate over all the key-value pairs in the count_map. For each key-value pair:
- The value count_map[rem] is the number of elements whose remainder with K is equal to ‘rem‘.
- For a valid pair to be formed, select any two numbers from the count_map[rem] numbers.
- The number of ways to select two numbers from ‘N‘ numbers is Nc2 = N * (N – 1) / 2.
- Add the answer of all key-value pairs and print ans.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
void countOfPairs( int * arr, int N, int K)
{
unordered_map< int , int > count_map;
for ( int index = 0; index < N; ++index) {
count_map[arr[index] % K]++;
}
int ans = 0;
for ( auto it : count_map) {
ans += (it.second * (it.second - 1)) / 2;
}
cout << ans << endl;
}
int main()
{
int K = 2;
int arr[] = { 1, 2, 3, 4 };
int N = sizeof arr / sizeof arr[0];
countOfPairs(arr, N, K);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void countOfPairs( int [] arr, int N, int K) {
HashMap<Integer, Integer> count_map =
new HashMap<Integer, Integer>();
for ( int index = 0 ; index < N; ++index) {
if (count_map.containsKey(arr[index] % K)) {
count_map.put(arr[index] % K,
count_map.get(arr[index] % K) + 1 );
} else {
count_map.put(arr[index] % K, 1 );
}
}
int ans = 0 ;
for (Map.Entry<Integer, Integer> it : count_map.entrySet()) {
ans += (it.getValue() * (it.getValue() - 1 )) / 2 ;
}
System.out.print(ans + "\n" );
}
public static void main(String[] args) {
int K = 2 ;
int arr[] = { 1 , 2 , 3 , 4 };
int N = arr.length;
countOfPairs(arr, N, K);
}
}
|
Python3
def countOfPairs(arr, N, K):
count_map = {}
for index in range (N):
if ( not arr[index] % K in count_map):
count_map[arr[index] % K] = 1
else :
count_map[arr[index] % K] + = 1
ans = 0
for val in count_map.values():
ans + = (val * (val - 1 )) / / 2
print (ans)
K = 2
arr = [ 1 , 2 , 3 , 4 ]
N = len (arr)
countOfPairs(arr, N, K)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static void countOfPairs( int [] arr, int N, int K) {
Dictionary< int , int > count_map =
new Dictionary< int , int >();
for ( int index = 0; index < N; ++index) {
if (count_map.ContainsKey(arr[index] % K)) {
count_map[arr[index] % K] =
count_map[arr[index] % K] + 1;
} else {
count_map.Add(arr[index] % K, 1);
}
}
int ans = 0;
foreach (KeyValuePair< int , int > it in count_map) {
ans += (it.Value * (it.Value - 1)) / 2;
}
Console.Write(ans + "\n" );
}
public static void Main(String[] args) {
int K = 2;
int []arr = { 1, 2, 3, 4 };
int N = arr.Length;
countOfPairs(arr, N, K);
}
}
|
Javascript
<script>
function countOfPairs(arr, N, K) {
let count_map = new Map();
for (let index = 0; index < N; ++index) {
if (!count_map.has(arr[index] % K))
count_map.set(arr[index] % K, 1);
else
count_map.set(arr[index] % K, count_map.get(arr[index] % K) + 1)
}
let ans = 0;
for (let [key, value] of count_map) {
ans += (value * (value - 1)) / 2;
}
document.write(ans + '<br>' );
}
let K = 2;
let arr = [1, 2, 3, 4];
let N = arr.length;
countOfPairs(arr, N, K);
</script>
|
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Last Updated :
30 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...