Count pairs in an array such that the absolute difference between them is ≥ K
Last Updated :
07 Jun, 2022
Given an array arr[] and an integer K, the task is to find the count of pairs (arr[i], arr[j]) from the array such that |arr[i] – arr[j]| ? K. Note that (arr[i], arr[j]) and arr[j], arr[i] will be counted only once.
Examples:
Input: arr[] = {1, 2, 3, 4}, K = 2
Output: 3
All valid pairs are (1, 3), (1, 4) and (2, 4)
Input: arr[] = {7, 4, 12, 56, 123}, K = 50
Output: 5
Approach: Sort the given array. Now for every element arr[i], find the first element on the right arr[j] such that (arr[j] – arr[i]) ? K. This is because after this element, every element will satisfy the same condition with arr[i] as the array is sorted and the count of elements that will make a valid pair with arr[i] will be (N – j) where N is the size of the given array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int count( int arr[], int n, int k)
{
sort(arr, arr + n);
int cnt = 0;
int i = 0, j = 1;
while (i < n && j < n) {
j = (j <= i) ? (i + 1) : j;
while (j < n && (arr[j] - arr[i]) < k)
j++;
cnt += (n - j);
i++;
}
return cnt;
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 2;
cout << count(arr, n, k);
return 0;
}
|
Java
import java.util.*;
class solution
{
static int count( int arr[], int n, int k)
{
Arrays.sort(arr);
int cnt = 0 ;
int i = 0 , j = 1 ;
while (i < n && j < n) {
j = (j <= i) ? (i + 1 ) : j;
while (j < n && (arr[j] - arr[i]) < k)
j++;
cnt += (n - j);
i++;
}
return cnt;
}
public static void main(String args[])
{
int arr[] = { 1 , 2 , 3 , 4 };
int n = arr.length;
int k = 2 ;
System.out.println(count(arr, n, k));
}
}
|
Python3
def count(arr, n, k) :
arr.sort();
cnt = 0 ;
i = 0 ; j = 1 ;
while (i < n and j < n) :
if j < = i :
j = i + 1
else :
j = j
while (j < n and (arr[j] - arr[i]) < k) :
j + = 1 ;
cnt + = (n - j);
i + = 1 ;
return cnt;
if __name__ = = "__main__" :
arr = [ 1 , 2 , 3 , 4 ];
n = len (arr);
k = 2 ;
print (count(arr, n, k));
|
C#
using System;
class GFG
{
static int count( int []arr, int n, int k)
{
Array.Sort(arr);
int cnt = 0;
int i = 0, j = 1;
while (i < n && j < n)
{
j = (j <= i) ? (i + 1) : j;
while (j < n && (arr[j] - arr[i]) < k)
j++;
cnt += (n - j);
i++;
}
return cnt;
}
static public void Main ()
{
int []arr = { 1, 2, 3, 4 };
int n = arr.Length;
int k = 2;
Console.Write(count(arr, n, k));
}
}
|
Javascript
<script>
function count(arr, n, k) {
arr.sort();
var cnt = 0;
var i = 0;
var j = 1;
while (i < n && j < n) {
if (j <= i)
j = i + 1
else
j = j
while (j < n && (arr[j] - arr[i]) < k)
j += 1;
cnt += (n - j);
i += 1;
}
return cnt;
}
var arr = [ 1, 2, 3, 4 ];
var n = arr.length;
var k = 2;
document.write(count(arr, n, k));
</script>
|
Time Complexity: O(n * log n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...