Pairs with difference k | Practice | GeeksforGeeks

Given an array Arr of N positive integers. Find the number of pairs of integers whose difference is equal to a given number K.
Note: (a, b) and (b, a) are considered same. Also, same numbers at different indices are considered different.
Example 1:
Input: 
N = 5
Arr[] = {1, 5, 3, 4, 2}
K = 3
Output: 2
Explanation: There are 2 pairs with difference 3, 
             the pairs are {1, 4} and {5, 2} 
Example 2:
Input: 
N = 6
Arr[] = {8, 12, 16, 4, 0, 20}
K = 4
Output: 5
Explanation: There are 5 pairs with difference 4, 
             the pairs are {0, 4}, {4, 8}, 
             {8, 12}, {12, 16} and {16, 20} 
Your Task:  
You don't need to read input or print anything. Your task is to complete the function countPairsWithDiffK() which takes the array arr[], n and k as inputs and returns an integer denoting the answer.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(max(Arri))
Constraints:
1 <= N <= 105
0 <= K <= 105
0 <= Arri <= 105
 
-1
soumyabrata0242 months ago
Given input is wrong seems
3 0 
2 3
 
leading test case failure
-1
chessnoobdj4 months ago
C++
int countPairsWithDiffK(int arr[], int n, int k) {
	int maxEle = *max_element(arr, arr+n);
	vector <int> hash(maxEle + 1, 0);
    for (int i = 0; i < n; i++)
        hash[arr[i]]++;
    int count = 0;
    for (int i = 0; i <= maxEle; i++) {
        if (hash[i]) {
            if (k == 0)
                count += (hash[i] * (hash[i] - 1)) / 2;
            else if (i + k <= maxEle)
                count += (hash[i] * hash[i + k]);
        }
    }
    return count;
}
0
shahzdor8 months ago
shahzdor
Python solution:Execution time:1.4 sec
from collections import Counterclass Solution:  def countPairsWithDiffK(self,arr, n, k):    if k==0:      dict1=Counter(arr)      count=0      for i in dict1:        if dict1[i]>1:          count+=(dict1[i]*(dict1[i]-1))/2      return int(count)    else:      arr.sort()      dict1=dict()      count=0      for i in arr:        if i not in dict1:          dict1[i]=1          if i-k in dict1:            count+=dict1[i-k]        else:          dict1[i]+=1          if i-k in dict1:            count+=dict1[i-k]        return count
0
Arnav Singh11 months ago
Arnav Singh
int maxEle = 0;    for (int i = 0; i < n; i++) {        maxEle = max(maxEle, arr[i]);    }    vector<int> hash(maxEle + 1, 0);    for (int i = 0; i < n; i++) {        hash[arr[i]]++;    }    int count = 0;    for (int i = 0; i <= maxEle; i++) {        if (hash[i]) {            if (i == i + k) {                count += (hash[i] * (hash[i] - 1)) / 2;            } else if (i + k <= maxEle) {                count += (hash[i] * hash[i + k]);            }        }    }    return count;}
0
Hemakshi Manchandia2 years ago
Hemakshi Manchandia
I am getting TLE by using map. Is there any other better approach to solve this
0
shourya2 years ago
shourya
I am getting segmentation fault please tell ??int countPairsWithDiffK(int arr[], int n, int k) {    int maxi =0 ;    for(int i=0 ; i<n ;i++){="" if(arr[i]="">maxi)            maxi=arr[i];    }    int a[maxi+1]={0};    for(int i=0 ; i<n ;i++){="" a[arr[i]]++;="" }="" int="" count="0" ;="" for(int="" i="0" ;="" i<maxi+1="" ;i++){="" if(i+k="">maxi)            break;        if(k==0 && a[i]>0){            count+=(int)(a[i]*(a[i]-1))/2;        }        else if(k!=0 && a[i]>0 && a[i+k]>0 ){            count+=a[i]*a[i+k];        }    }    return count;}
0
Goutham Reddy2 years ago
Goutham Reddy
@GeeksforGeeks
I have a doubt
when input is:15 02 2 2 2 2is the output:20(or)output:25??
0
krishnaballabh2 years ago
krishnaballabh
for i in range(int(input())):    n,k = map(int,input().split())    l = list(map(int,input().split()))    c = 0    for i in range(0,len(l)-1):        for j in range(i+1,len(l)):            if abs(l[i]-l[j]) == k:                c+=1    print(c)
0
krishnaballabh2 years ago
krishnaballabh
#code#time 0.05for i in range(int(input())):    n,k = map(int,input().split())    l = list(map(int,input().split()))    c = 0    for i in range(0,len(l)-1):        for j in range(i+1,len(l)):            if abs(l[i]-l[j]) == k:                c+=1    print(c)
0
Shivam Bhardwaj2 years ago
Shivam Bhardwaj
simple c++ solution using differencetime: 0.01https://ide.geeksforgeeks.o...
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.