Given an integer array and a positive integer k, count all distinct pairs with difference equal to k.
Examples:
Input: arr[] = {1, 5, 3, 4, 2}, k = 3
Output: 2
There are 2 pairs with difference 3, the pairs are {1, 4} and {5, 2}
Input: arr[] = {8, 12, 16, 4, 0, 20}, k = 4
Output: 5
There are 5 pairs with difference 4, the pairs are {0, 4}, {4, 8},
{8, 12}, {12, 16} and {16, 20}
Method 1 (Simple)
A simple solution is to consider all pairs one by one and check difference between every pair. Following program implements the simple solution. We run two loops: the outer loop picks the first element of pair, the inner loop looks for the other element. This solution doesn’t work if there are duplicates in array as the requirement is to count only distinct pairs.
C++
/* A simple program to count pairs with difference k*/#include<iostream>using namespace std;int countPairsWithDiffK(int arr[], int n, int k){ int count = 0; // Pick all elements one by one for (int i = 0; i < n; i++) { // See if there is a pair of this picked element for (int j = i+1; j < n; j++) if (arr[i] - arr[j] == k || arr[j] - arr[i] == k ) count++; } return count;}// Driver program to test above functionint main(){ int arr[] = {1, 5, 3, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout << "Count of pairs with given diff is " << countPairsWithDiffK(arr, n, k); return 0;} |
Java
// A simple Java program to //count pairs with difference kimport java.util.*;import java.io.*;class GFG { static int countPairsWithDiffK(int arr[], int n, int k) { int count = 0; // Pick all elements one by one for (int i = 0; i < n; i++) { // See if there is a pair // of this picked element for (int j = i + 1; j < n; j++) if (arr[i] - arr[j] == k || arr[j] - arr[i] == k) count++; } return count; } // Driver code public static void main(String args[]) { int arr[] = { 1, 5, 3, 4, 2 }; int n = arr.length; int k = 3; System.out.println("Count of pairs with given diff is " + countPairsWithDiffK(arr, n, k)); }}// This code is contributed // by Sahil_Bansall |
Python3
# A simple program to count pairs with difference kdef countPairsWithDiffK(arr, n, k): count = 0 # Pick all elements one by one for i in range(0, n): # See if there is a pair of this picked element for j in range(i+1, n) : if arr[i] - arr[j] == k or arr[j] - arr[i] == k: count += 1 return count# Driver programarr = [1, 5, 3, 4, 2]n = len(arr)k = 3print ("Count of pairs with given diff is ", countPairsWithDiffK(arr, n, k)) |
C#
// A simple C# program to count pairs with // difference kusing System;class GFG { static int countPairsWithDiffK(int []arr, int n, int k) { int count = 0; // Pick all elements one by one for (int i = 0; i < n; i++) { // See if there is a pair // of this picked element for (int j = i + 1; j < n; j++) if (arr[i] - arr[j] == k || arr[j] - arr[i] == k) count++; } return count; } // Driver code public static void Main() { int []arr = { 1, 5, 3, 4, 2 }; int n = arr.Length; int k = 3; Console.WriteLine("Count of pairs with " + " given diff is " + countPairsWithDiffK(arr, n, k)); }}// This code is contributed by Sam007. |
PHP
<?php// A simple PHP program to count // pairs with difference kfunction countPairsWithDiffK($arr, $n, $k){ $count = 0; // Pick all elements one by one for($i = 0; $i < $n; $i++) { // See if there is a pair of // this picked element for($j = $i + 1; $j < $n; $j++) if ($arr[$i] - $arr[$j] == $k or $arr[$j] - $arr[$i] == $k) $count++; } return $count;} // Driver Code $arr = array(1, 5, 3, 4, 2); $n = count($arr); $k = 3; echo "Count of pairs with given diff is " , countPairsWithDiffK($arr, $n, $k); // This code is contributed by anuj_67.?> |
Output :
Count of pairs with given diff is 2
Time Complexity of O(n2)
Method 2 (Use Sorting)
We can find the count in O(nLogn) time using a O(nLogn) sorting algorithm like Merge Sort, Heap Sort, etc. Following are the detailed steps.
1) Initialize count as 0 2) Sort all numbers in increasing order. 3) Remove duplicates from array. 4) Do following for each element arr[i] a) Binary Search for arr[i] + k in subarray from i+1 to n-1. b) If arr[i] + k found, increment count. 5) Return count.
C++
/* A sorting based program to count pairs with difference k*/#include <iostream>#include <algorithm>using namespace std;/* Standard binary search function */int binarySearch(int arr[], int low, int high, int x){ if (high >= low) { int mid = low + (high - low)/2; if (x == arr[mid]) return mid; if (x > arr[mid]) return binarySearch(arr, (mid + 1), high, x); else return binarySearch(arr, low, (mid -1), x); } return -1;}/* Returns count of pairs with difference k in arr[] of size n. */int countPairsWithDiffK(int arr[], int n, int k){ int count = 0, i; sort(arr, arr+n); // Sort array elements /* code to remove duplicates from arr[] */ // Pick a first element point for (i = 0; i < n-1; i++) if (binarySearch(arr, i+1, n-1, arr[i] + k) != -1) count++; return count;}// Driver program int main(){ int arr[] = {1, 5, 3, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout << "Count of pairs with given diff is " << countPairsWithDiffK(arr, n, k); return 0;} |
Java
// A sorting base java program to // count pairs with difference kimport java.util.*;import java.io.*;class GFG { // Standard binary search function // static int binarySearch(int arr[], int low, int high, int x) { if (high >= low) { int mid = low + (high - low) / 2; if (x == arr[mid]) return mid; if (x > arr[mid]) return binarySearch(arr, (mid + 1), high, x); else return binarySearch(arr, low, (mid - 1), x); } return -1; } // Returns count of pairs with // difference k in arr[] of size n. static int countPairsWithDiffK(int arr[], int n, int k) { int count = 0, i; // Sort array elements Arrays.sort(arr); // code to remove duplicates from arr[] // Pick a first element point for (i = 0; i < n - 1; i++) if (binarySearch(arr, i + 1, n - 1, arr[i] + k) != -1) count++; return count; } // Driver code public static void main(String args[]) { int arr[] = { 1, 5, 3, 4, 2 }; int n = arr.length; int k = 3; System.out.println("Count of pairs with given diff is " + countPairsWithDiffK(arr, n, k)); }}// This code is contributed by Sahil_Bansall |
Python
# A sorting based program to # count pairs with difference k# Standard binary search function def binarySearch(arr, low, high, x): if (high >= low): mid = low + (high - low)//2 if x == arr[mid]: return (mid) elif(x > arr[mid]): return binarySearch(arr, (mid + 1), high, x) else: return binarySearch(arr, low, (mid -1), x) return -1# Returns count of pairs with # difference k in arr[] of size n. def countPairsWithDiffK(arr, n, k): count = 0 arr.sort() # Sort array elements # code to remove # duplicates from arr[] # Pick a first element point for i in range (0, n - 2): if (binarySearch(arr, i + 1, n - 1, arr[i] + k) != -1): count += 1 return count# Driver Code arr= [1, 5, 3, 4, 2]n = len(arr)k = 3print ("Count of pairs with given diff is ", countPairsWithDiffK(arr, n, k)) # This code is contributed# by Shivi_Aggarwal |
C#
// A sorting base C# program to // count pairs with difference kusing System;class GFG { // Standard binary search function static int binarySearch(int []arr, int low, int high, int x) { if (high >= low) { int mid = low + (high - low) / 2; if (x == arr[mid]) return mid; if (x > arr[mid]) return binarySearch(arr, (mid + 1), high, x); else return binarySearch(arr, low, (mid - 1), x); } return -1; } // Returns count of pairs with // difference k in arr[] of size n. static int countPairsWithDiffK(int []arr, int n, int k) { int count = 0, i; // Sort array elements Array.Sort(arr); // code to remove duplicates from arr[] // Pick a first element point for (i = 0; i < n - 1; i++) if (binarySearch(arr, i + 1, n - 1, arr[i] + k) != -1) count++; return count; } // Driver code public static void Main() { int []arr = { 1, 5, 3, 4, 2 }; int n = arr.Length; int k = 3; Console.WriteLine("Count of pairs with" + " given diff is " + countPairsWithDiffK(arr, n, k)); }}// This code is contributed by Sam007. |
PHP
<?php// A sorting based PHP program to// count pairs with difference k// Standard binary search functionfunction binarySearch($arr, $low, $high, $x){ if ($high >= $low) { $mid = $low + ($high - $low)/2; if ($x == $arr[$mid]) return $mid; if ($x > $arr[$mid]) return binarySearch($arr, ($mid + 1), $high, $x); else return binarySearch($arr, $low, ($mid -1), $x); } return -1;}/* Returns count of pairs with difference k in arr[] of size n. */function countPairsWithDiffK($arr, $n, $k){ $count = 0; $i; // Sort array elements sort($arr); // Code to remove duplicates // from arr[] // Pick a first element point for ($i = 0; $i < $n - 1; $i++) if (binarySearch($arr, $i + 1, $n - 1, $arr[$i] + $k) != -1) $count++; return $count;} // Driver Code $arr = array(1, 5, 3, 4, 2); $n = count($arr); $k = 3; echo "Count of pairs with given diff is " , countPairsWithDiffK($arr, $n, $k); // This code is contributed by anuj-67.?> |
Output:
Count of pairs with given diff is 2
Time complexity: The first step (sorting) takes O(nLogn) time. The second step runs binary search n times, so the time complexity of second step is also O(nLogn). Therefore, overall time complexity is O(nLogn). The second step can be optimized to O(n), see this.
Method 3 (Use Self-balancing BST)
We can also a self-balancing BST like AVL tree or Red Black tree to solve this problem. Following is detailed algorithm.
1) Initialize count as 0. 2) Insert all elements of arr[] in an AVL tree. While inserting, ignore an element if already present in AVL tree. 3) Do following for each element arr[i]. a) Search for arr[i] + k in AVL tree, if found then increment count. b) Search for arr[i] - k in AVL tree, if found then increment count. c) Remove arr[i] from AVL tree.
Time complexity of above solution is also O(nLogn) as search and delete operations take O(Logn) time for a self-balancing binary search tree.
Method 4 (Use Hashing)
We can also use hashing to achieve the average time complexity as O(n) for many cases.
1) Initialize count as 0. 2) Insert all distinct elements of arr[] in a hash map. While inserting, ignore an element if already present in the hash map. 3) Do following for each element arr[i]. a) Look for arr[i] + k in the hash map, if found then increment count. b) Look for arr[i] - k in the hash map, if found then increment count. c) Remove arr[i] from hash table.
A very simple case where hashing works in O(n) time is the case where range of values is very small. For example, in the following implementation, range of numbers is assumed to be 0 to 99999. A simple hashing technique to use values as index can be used.
CPP
/* An efficient program to count pairs with difference k when the range numbers is small */#define MAX 100000int countPairsWithDiffK(int arr[], int n, int k){ int count = 0; // Initialize count // Initialize empty hashmap. bool hashmap[MAX] = {false}; // Insert array elements to hashmap for (int i = 0; i < n; i++) hashmap[arr[i]] = true; for (int i = 0; i < n; i++) { int x = arr[i]; if (x - k >= 0 && hashmap[x - k]) count++; if (x + k < MAX && hashmap[x + k]) count++; hashmap[x] = false; } return count;} |
Method 5 (Use Sorting)
- Sort the array arr
- Take two pointers, l and r, both pointing to 1st element
- Take the difference arr[r] – arr[l]
- If value diff is K, increment count and move both pointers to next element
- if value diff > k, move l to next element
- if value diff < k, move r to next element
- return count
C++
/* A sorting based program to count pairs with difference k*/#include <iostream>#include <algorithm>using namespace std; /* Returns count of pairs with difference k in arr[] of size n. */int countPairsWithDiffK(int arr[], int n, int k){ int count = 0; sort(arr, arr+n); // Sort array elements int l = 0; int r = 0; while(r < n) { if(arr[r] - arr[l] == k) { count++; l++; r++; } else if(arr[r] - arr[l] > k) l++; else // arr[r] - arr[l] < sum r++; } return count;}// Driver program to test above functionint main(){ int arr[] = {1, 5, 3, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout << "Count of pairs with given diff is " << countPairsWithDiffK(arr, n, k); return 0;} |
Java
// A sorting based Java program to // count pairs with difference kimport java.util.*;class GFG {/* Returns count of pairs withdifference k in arr[] of size n. */static int countPairsWithDiffK(int arr[], int n, int k){ int count = 0; Arrays.sort(arr); // Sort array elements int l = 0; int r = 0; while(r < n) { if(arr[r] - arr[l] == k) { count++; l++; r++; } else if(arr[r] - arr[l] > k) l++; else // arr[r] - arr[l] < sum r++; } return count;}// Driver program to test above functionpublic static void main(String[] args){ int arr[] = {1, 5, 3, 4, 2}; int n = arr.length; int k = 3; System.out.println("Count of pairs with given diff is " + countPairsWithDiffK(arr, n, k));}}// This code is contributed by Prerna Saini |
Python3
# A sorting based program to # count pairs with difference kdef countPairsWithDiffK(arr,n,k): count =0 # Sort array elements arr.sort() l =0 r=0 while r<n: if arr[r]-arr[l]==k: count+=1 l+=1 r+=1 # arr[r] - arr[l] < sum elif arr[r]-arr[l]>k: l+=1 else: r+=1 return count# Driver codeif __name__=='__main__': arr = [1, 5, 3, 4, 2] n = len(arr) k = 3 print("Count of pairs with given diff is ", countPairsWithDiffK(arr, n, k))# This code is contributed by # Shrikant13 |
C#
// A sorting based C# program to count // pairs with difference kusing System;class GFG { /* Returns count of pairs with difference k in arr[] of size n. */ static int countPairsWithDiffK(int []arr, int n, int k) { int count = 0; // Sort array elements Array.Sort(arr); int l = 0; int r = 0; while(r < n) { if(arr[r] - arr[l] == k) { count++; l++; r++; } else if(arr[r] - arr[l] > k) l++; else // arr[r] - arr[l] < sum r++; } return count; } // Driver program to test above function public static void Main() { int []arr = {1, 5, 3, 4, 2}; int n = arr.Length; int k = 3; Console.Write("Count of pairs with " + "given diff is " + countPairsWithDiffK(arr, n, k)); }}// This code is contributed by nitin mittal. |
PHP
<?php// A sorting based program to count// pairs with difference k// Returns count of pairs with // difference k in arr[] of size n.function countPairsWithDiffK( $arr, $n, $k){ $count = 0; // Sort array elements sort($arr); $l = 0; $r = 0; while($r < $n) { if($arr[$r] - $arr[$l] == $k) { $count++; $l++; $r++; } else if($arr[$r] - $arr[$l] > $k) $l++; // arr[r] - arr[l] < k else $r++; } return $count;} // Driver Code $arr = array(1, 5, 3, 4, 2); $n =count($arr); $k = 3; echo "Count of pairs with given diff is " , countPairsWithDiffK($arr, $n, $k); // This code is contributed by anuj_67,?> |
Output:
Count of pairs with given diff is 2
Time Complexity: O(nlogn)
Method 6(Using Binary Search)(Works with duplicates in the array):
1) Initialize count as 0.
2) Sort all numbers in increasing order.
4) Do following for each element arr[i]
a) Binary Search for the first occurrence of arr[i] + k in the sub array arr[i+1, N-1], let this index be ‘X’.
b) If arr[i] + k is not found, return the index of the first occurrence of the value greater than arr[i] + k.
c) Repeat steps a and b to search for the first occurrence of arr[i] + k + 1, let this index be ‘Y’.
d) Increment count with ‘Y – X’.
5) Return count.
Java
/*package whatever //do not write package name here */import java.io.*;class GFG { static int BS(int[] arr, int X, int low) { int high = arr.length - 1; int ans = arr.length; while(low <= high) { int mid = low + (high - low) / 2; if(arr[mid] >= X) { ans = mid; high = mid - 1; } else low = mid + 1; } return ans; } static int countPairsWithDiffK(int[] arr, int N, int k) { int count = 0; Arrays.sort(arr); for(int i = 0 ; i < N ; ++i) { int X = BS(arr, arr[i] + k, i + 1); if(X != N) { int Y = BS(arr, arr[i] + k + 1, i + 1); count += Y - X; } } return count; } public static void main (String[] args) { int arr[] = {1, 3, 5, 8, 6, 4, 6}; int n = arr.length; int k = 2; System.out.println("Count of pairs with given diff is " + countPairsWithDiffK(arr, n, k)); }} |
Time Complexity: O(N * log(N))
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Count all distinct pairs with product equal to K
- Count all distinct pairs of repeating elements from the array for every array element
- Count of replacements required to make the sum of all Pairs of given type from the Array equal
- Make all array elements equal by repeated subtraction of absolute difference of pairs from their maximum
- Count the pairs in an array such that the difference between them and their indices is equal
- Count pairs from an array having product of their sum and difference equal to 0
- Count pairs from an array having product of their sum and difference equal to 1
- Count pairs formed by distinct element sub-arrays
- Count number of distinct pairs whose sum exists in the given array
- Count distinct pairs from two arrays having same sum of digits
- Count of distinct Strings possible by swapping prefixes of pairs of Strings from the Array
- Count of pairs between two arrays such that the sums are distinct
- Count of distinct possible pairs such that the element from A is greater than the element from B
- Count pairs whose product contains single distinct prime factor
- Count ways to partition a string such that both parts have equal distinct characters
- Count the number of strings in an array whose distinct characters are less than equal to M
- Given an array of pairs, find all symmetric pairs in it
- Count of all pairs in an Array with minimum absolute difference
- Count all disjoint pairs having absolute difference at least K from a given array
- Print all pairs in an unsorted array with equal sum

