Count all distinct pairs with difference equal to K | Set 2
Last Updated :
14 Apr, 2022
Given an integer array arr[] and a positive integer K, the task is to count all distinct pairs with differences equal to K.
Examples:
Input: arr[ ] = {1, 5, 3, 4, 2}, K = 3
Output: 2
Explanation: There are 2 distinct pairs with difference 3, the pairs are {1, 4} and {5, 2}
Input: arr[] = {8, 12, 16, 4, 0, 20}, K = 4
Output: 5
Explanation: There are 5 unique pairs with difference 4.
The pairs are {0, 4}, {4, 8}, {8, 12}, {12, 16} and {16, 20}
The naive approach and approach based on sorting and binary search are mentioned on the Set 1 of this article.
Approach: The time complexity for this problem can be reduced to have a linear complexity in average case by using hashing with the help of unordered maps as per the following idea:
For forming such unique pairs, if traversed from the smallest element, an element (say x) will form such a pair with another element having value (x+K).
When the difference K = 0 then the elements having frequency more than 1 will be able to form pairs with itself.
Follow the steps mentioned below to solve the problem:
- Initialize an unordered map and push all the array elements into the map.
- If the given value of K is 0:
- If the frequency of current element x is greater than 1, increment count by 1.
- Else try the same for the other elements.
- If the given value of K is not 0:
- Search x + K in the map and if it is found, increment the count by 1.
- Else try for the other elements.
- Return the count.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int TotalPairs(vector< int > nums, int K)
{
unordered_map< int , int > mp;
int cnt = 0;
for ( int i = 0; i < nums.size(); i++) {
mp[nums[i]]++;
}
if (K == 0) {
for ( auto i : mp) {
if (i.second > 1)
cnt++;
}
}
else {
for ( auto i : mp) {
if (mp.find(i.first + K)
!= mp.end()) {
cnt++;
}
}
}
return cnt;
}
int main()
{
vector< int > arr = { 8, 12, 16, 4, 0, 20 };
int K = 4;
int ans = TotalPairs(arr, K);
cout << ans;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static int TotalPairs( int nums[], int K)
{
Map<Integer, Integer> mp
= new HashMap<Integer, Integer>();
int cnt = 0 ;
for ( int i = 0 ; i < nums.length; i++) {
if (mp.get(nums[i]) != null )
mp.put(nums[i], mp.get(nums[i]) + 1 );
else
mp.put(nums[i], 1 );
}
if (K == 0 ) {
for (Map.Entry<Integer, Integer> it :
mp.entrySet()) {
if (it.getValue() > 1 )
cnt++;
}
}
else {
for (Map.Entry<Integer, Integer> it :
mp.entrySet()) {
if (mp.get(it.getKey() + K) != null ) {
cnt++;
}
}
}
return cnt;
}
public static void main(String[] args)
{
int arr[] = { 8 , 12 , 16 , 4 , 0 , 20 };
int K = 4 ;
int ans = TotalPairs(arr, K);
System.out.print(ans);
}
}
|
Python3
def TotalPairs(nums, K):
mp = dict ()
cnt = 0
for i in range ( len (nums)):
if nums[i] in mp:
mp[nums[i]] + = 1
else :
mp[nums[i]] = 1
if K = = 0 :
for i in mp:
if mp[i] > 1 :
cnt + = 1
else :
for i in mp:
if i + K in mp:
cnt + = 1
return cnt
arr = [ 8 , 12 , 16 , 4 , 0 , 20 ]
K = 4
ans = TotalPairs(arr, K)
print (ans)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static int TotalPairs( int [] nums, int K)
{
Dictionary< int , int > mp
= new Dictionary< int , int >();
int cnt = 0;
for ( int i = 0; i < nums.Length; i++) {
if (mp.ContainsKey(nums[i]))
mp[nums[i]] += 1;
else
mp[nums[i]] = 1;
}
if (K == 0) {
foreach (KeyValuePair< int , int > it in mp)
{
if (it.Value > 1)
cnt++;
}
}
else {
foreach (KeyValuePair< int , int > it in mp)
{
if (mp.ContainsKey(it.Key + K)) {
cnt++;
}
}
}
return cnt;
}
public static void Main( string [] args)
{
int [] arr = { 8, 12, 16, 4, 0, 20 };
int K = 4;
int ans = TotalPairs(arr, K);
Console.Write(ans);
}
}
|
Javascript
<script>
function TotalPairs(nums, K)
{
var mp = {};
var cnt = 0;
for ( var i = 0; i < nums.length; i++) {
if (mp.hasOwnProperty(nums[i]))
mp[nums[i]] += 1;
else
mp[nums[i]] = 1;
}
if (K == 0) {
for (const i of Object.keys(mp)) {
console.log(i, mp[i], cnt);
if (mp[i] > 1)
cnt += 1;
}
}
else {
for (const i of Object.keys(mp)) {
if (mp.hasOwnProperty(parseInt(i) + K))
{
cnt += 1;
}
}
}
return cnt;
}
var arr = [ 8, 12, 16, 4, 0, 20 ];
var K = 4;
document.write(TotalPairs(arr, K));
</script>
|
Time Complexity: O(N) [In average case, because the average case time complexity of unordered map is O(1)]
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...