Given an integer array and a positive integer k, count all distinct pairs with differences 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++
#include <iostream>
using namespace std;
int countPairsWithDiffK( int arr[], int n, int k)
{
int count = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++)
if (arr[i] - arr[j] == k
|| arr[j] - arr[i] == k)
count++;
}
return count;
}
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;
}
|
C
#include <stdio.h>
int countPairsWithDiffK( int arr[], int n, int k)
{
int count = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++)
if (arr[i] - arr[j] == k
|| arr[j] - arr[i] == k)
count++;
}
return count;
}
int main()
{
int arr[] = { 1, 5, 3, 4, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
printf ( "Count of pairs with given diff is %d" ,
countPairsWithDiffK(arr, n, k));
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG {
static int countPairsWithDiffK( int arr[],
int n, int k)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++)
{
for ( int j = i + 1 ; j < n; j++)
if (arr[i] - arr[j] == k ||
arr[j] - arr[i] == k)
count++;
}
return count;
}
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));
}
}
|
Python3
def countPairsWithDiffK(arr, n, k):
count = 0
for i in range ( 0 , n):
for j in range (i + 1 , n) :
if arr[i] - arr[j] = = k or arr[j] - arr[i] = = k:
count + = 1
return count
arr = [ 1 , 5 , 3 , 4 , 2 ]
n = len (arr)
k = 3
print ( "Count of pairs with given diff is " ,
countPairsWithDiffK(arr, n, k))
|
C#
using System;
class GFG {
static int countPairsWithDiffK( int []arr,
int n, int k)
{
int count = 0;
for ( int i = 0; i < n; i++)
{
for ( int j = i + 1; j < n; j++)
if (arr[i] - arr[j] == k ||
arr[j] - arr[i] == k)
count++;
}
return count;
}
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));
}
}
|
PHP
<?php
function countPairsWithDiffK( $arr , $n ,
$k )
{
$count = 0;
for ( $i = 0; $i < $n ; $i ++)
{
for ( $j = $i + 1; $j < $n ; $j ++)
if ( $arr [ $i ] - $arr [ $j ] == $k or
$arr [ $j ] - $arr [ $i ] == $k )
$count ++;
}
return $count ;
}
$arr = array (1, 5, 3, 4, 2);
$n = count ( $arr );
$k = 3;
echo "Count of pairs with given diff is "
, countPairsWithDiffK( $arr , $n , $k );
?>
|
Javascript
<script>
function countPairsWithDiffK(arr, n, k)
{
count = 0;
for (let i = 0; i < n; i++)
{
for (let j = i+1; j < n; j++)
if (arr[i] - arr[j] == k ||
arr[j] - arr[i] == k )
count++;
}
return count;
}
arr = new Array(1, 5, 3, 4, 2);
n = arr.length;
k = 3;
document.write( "Count of pairs with given diff is "
+ countPairsWithDiffK(arr, n, k));
</script>
|
Output
Count of pairs with given diff is 2
Time Complexity: O(n2)
Auxiliary Space: O(1), since no extra space has been taken.
Method 2 (Use Sorting)
We can find the count in O(nLogn) time using O(nLogn) sorting algorithms 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++
#include <iostream>
#include <algorithm>
using namespace std;
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;
}
int countPairsWithDiffK( int arr[], int n, int k)
{
int count = 0, i;
sort(arr, arr+n);
for (i = 0; i < n; i++){
while (i - 1 >= 0 && arr[i] == arr[i - 1]) i++;
if (binarySearch(arr, i+1, n-1, arr[i] + k) != -1)
count++;
}
return count;
}
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
import java.io.*;
import java.util.*;
class GFG {
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 ;
}
static int countPairsWithDiffK( int arr[], int n, int k)
{
int count = 0 , i;
Arrays.sort(arr);
for (i = 0 ; i < n; i++) {
while (i - 1 >= 0 && arr[i] == arr[i - 1 ])
i++;
if (binarySearch(arr, i + 1 , n - 1 , arr[i] + k)
!= - 1 )
count++;
}
return count;
}
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));
}
}
|
Python
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
def countPairsWithDiffK(arr, n, k):
count = 0
arr.sort()
i = 0
while (i < n):
while (i - 1 > = 0 and arr[i] = = arr[i - 1 ]):
i + = 1
if (binarySearch(arr, i + 1 , n - 1 ,
arr[i] + k) ! = - 1 ):
count + = 1
i + = 1
return count
arr = [ 1 , 5 , 3 , 4 , 2 ]
n = len (arr)
k = 3
print ( "Count of pairs with given diff is " ,
countPairsWithDiffK(arr, n, k))
|
C#
using System;
class GFG {
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;
}
static int countPairsWithDiffK( int [] arr, int n, int k)
{
int count = 0, i;
Array.Sort(arr);
for (i = 0; i < n; i++) {
while (i - 1 >= 0 && arr[i] == arr[i - 1])
i++;
if (binarySearch(arr, i + 1, n - 1, arr[i] + k)
!= -1)
count++;
}
return count;
}
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));
}
}
|
PHP
<?php
function 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;
}
function countPairsWithDiffK( $arr , $n , $k )
{
$count = 0;
$i ;
sort( $arr );
for ( $i = 0; $i < $n ; $i ++){
while ( $i - 1 >= 0 && $arr [ $i ] == $arr [ $i - 1]) $i ++;
if (binarySearch( $arr , $i + 1, $n - 1,
$arr [ $i ] + $k ) != -1)
$count ++;
}
return $count ;
}
$arr = array (1, 5, 3, 4, 2);
$n = count ( $arr );
$k = 3;
echo "Count of pairs with given diff is "
, countPairsWithDiffK( $arr , $n , $k );
?>
|
Javascript
<script>
function binarySearch(arr, low, high, x)
{
if (high >= low)
{
let mid = low + Math.floor((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;
}
function countPairsWithDiffK(arr, n, k)
{
let count = 0, i;
arr.sort((a, b) => a - b);
for (i = 0; i < n; i++){
while (i - 1 >= 0 && arr[i] == arr[i - 1]) i++;
if (binarySearch(arr, i+1, n-1, arr[i] + k) != -1)
count++;
}
return count;
}
let arr = [1, 5, 3, 4, 2];
let n = arr.length;
let k = 3;
document.write( "Count of pairs with given diff is "
+ countPairsWithDiffK(arr, n, k));
</script>
|
Output
Count of pairs with given diff is 2
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.
Time Complexity: O(nlogn)
Auxiliary Space: O(logn)
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 a 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 the 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 a range of values is very small. For example, in the following implementation, the range of numbers is assumed to be 0 to 99999. A simple hashing technique to use values as an index can be used.
C++
#define MAX 100000
int countPairsWithDiffK( int arr[], int n, int k)
{
int count = 0;
bool hashmap[MAX] = { false };
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;
}
|
Java
static int MAX= 100000 ;
public static int countPairsWithDiffK( int arr[], int n, int k)
{
int count = 0 ;
boolean hashmap[MAX] = { false };
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;
}
|
Python3
MAX = 100000 ;
def countPairsWithDiffK(arr, n, k):
count = 0 ;
hashmap = [ False for i in range ( MAX )];
for i in range (n):
hashmap[arr[i]] = True ;
for i in range (n):
x = arr[i];
if (x - k > = 0 and hashmap[x - k]):
count + = 1 ;
if (x + k < MAX and hashmap[x + k]):
count + = 1 ;
hashmap[x] = False ;
return count;
|
C#
static int MAX=100000;
public static int countPairsWithDiffK( int []arr, int n, int k)
{
int count = 0;
bool hashmap[MAX] = { false };
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;
}
|
Javascript
<script>
var MAX = 100000;
function countPairsWithDiffK(arr, n, k)
{
var count = 0;
var hashmap = Array(MAX).fill( false );
for ( var i = 0; i < n; i++)
hashmap[arr[i]] = true ;
for ( var i = 0; i < n; i++)
{
var x = arr[i];
if (x - k >= 0 && hashmap[x - k])
count++;
if (x + k < MAX && hashmap[x + k])
count++;
hashmap[x] = false ;
}
return count;
}
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
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++
#include <iostream>
#include <algorithm>
using namespace std;
int countPairsWithDiffK( int arr[], int n, int k)
{
int count = 0;
sort(arr, arr+n);
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
r++;
}
return count;
}
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
import java.util.*;
class GFG {
static int countPairsWithDiffK( int arr[], int n,
int k)
{
int count = 0 ;
Arrays.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
r++;
}
return count;
}
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));
}
}
|
Python3
def countPairsWithDiffK(arr,n,k):
count = 0
arr.sort()
l = 0
r = 0
while r<n:
if arr[r] - arr[l] = = k:
count + = 1
l + = 1
r + = 1
elif arr[r] - arr[l]>k:
l + = 1
else :
r + = 1
return count
if __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))
|
C#
using System;
class GFG {
static int countPairsWithDiffK( int []arr,
int n, int k)
{
int count = 0;
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
r++;
}
return count;
}
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));
}
}
|
PHP
<?php
function countPairsWithDiffK( $arr , $n , $k )
{
$count = 0;
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 ++;
else
$r ++;
}
return $count ;
}
$arr = array (1, 5, 3, 4, 2);
$n = count ( $arr );
$k = 3;
echo "Count of pairs with given diff is "
, countPairsWithDiffK( $arr , $n , $k );
?>
|
Javascript
<script>
function countPairsWithDiffK(arr, n, k)
{
let count = 0;
arr.sort();
let l = 0;
let r = 0;
while (r < n)
{
if (arr[r] - arr[l] == k)
{
count++;
l++;
r++;
}
else if (arr[r] - arr[l] > k)
l++;
else
r++;
}
return count;
}
let arr = [1, 5, 3, 4, 2];
let n = arr.length;
let k = 3;
document.write( "Count of pairs with given diff is " +
countPairsWithDiffK(arr, n, k));
</script>
|
Output
Count of pairs with given diff is 2
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
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.
C++
#include <bits/stdc++.h>
using namespace std;
int BS( int arr[], int X, int low, int N)
{
int high = N - 1;
int ans = N;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] >= X) {
ans = mid;
high = mid - 1;
}
else
low = mid + 1;
}
return ans;
}
int countPairsWithDiffK( int arr[], int N, int k)
{
int count = 0;
sort(arr, arr + N);
for ( int i = 0; i < N; ++i) {
int X = BS(arr, arr[i] + k, i + 1, N);
if (X != N) {
int Y = BS(arr, arr[i] + k + 1, i + 1, N);
count += Y - X;
}
}
return count;
}
int main()
{
int arr[] = { 1, 3, 5, 8, 6, 4, 6 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 2;
cout << "Count of pairs with given diff is "
<< countPairsWithDiffK(arr, n, k);
return 0;
}
|
Java
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));
}
}
|
Python3
def BS(arr, X, low):
high = len (arr) - 1 ;
ans = len (arr);
while (low < = high):
mid = low + (high - low) / / 2 ;
if (arr[mid] > = X):
ans = mid;
high = mid - 1 ;
else :
low = mid + 1 ;
return ans;
def countPairsWithDiffK(arr, N, k):
count = 0 ;
arr.sort();
for i in range (N):
X = BS(arr, arr[i] + k, i + 1 );
if (X ! = N):
Y = BS(arr, arr[i] + k + 1 , i + 1 );
count + = Y - X;
return count;
if __name__ = = '__main__' :
arr = [ 1 , 3 , 5 , 8 , 6 , 4 , 6 ];
n = len (arr);
k = 2 ;
print ( "Count of pairs with given diff is " , countPairsWithDiffK(arr, n, k));
|
C#
using System;
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;
Array.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;
Console.WriteLine( "Count of pairs with given diff is " +
countPairsWithDiffK(arr, n, k));
}
}
|
Javascript
<script>
function BS(arr, X, low)
{
let high = arr.length - 1;
let ans = arr.length;
while (low <= high)
{
let mid = low + (high - low) / 2;
if (arr[mid] >= X)
{
ans = mid;
high = mid - 1;
}
else low = mid + 1;
}
return ans;
}
function countPairsWithDiffK(arr, N, k)
{
let count = 2;
arr.sort();
for (let i = 0 ; i < N ; ++i)
{
let X = BS(arr, arr[i] + k, i + 1);
if (X != N)
{
let Y = BS(arr, arr[i] + k + 1,
i + 1);
count += Y - X;
}
}
return count;
}
let arr = [ 1, 3, 5, 8, 6, 4, 6 ];
let n = arr.length;
let k = 3;
document.write( "Count of pairs with given diff is " +
countPairsWithDiffK(arr, n, k));
</script>
|
Output
Count of pairs with given diff is 6
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!