Given an array of n integers, We need to find all pairs with a difference less than k
Examples :
Input : a[] = {1, 10, 4, 2}
K = 3
Output : 2
We can make only two pairs
with difference less than 3.
(1, 2) and (4, 2)
Input : a[] = {1, 8, 7}
K = 7
Output : 2
Pairs with difference less than 7
are (1, 7) and (8, 7)
Method 1 (Simple): Run two nested loops. The outer loop picks every element x one by one. The inner loop considers all elements after x and checks if the difference is within limits or not.
Implementation:
// CPP code to find count of Pairs with
// difference less than K.
#include <bits/stdc++.h>
using namespace std;
int countPairs(int a[], int n, int k)
{
int res = 0;
for (int i = 0; i < n; i++)
for (int j=i+1; j<n; j++)
if (abs(a[j] - a[i]) < k)
res++;
return res;
}
// Driver code
int main()
{
int a[] = {1, 10, 4, 2};
int k = 3;
int n = sizeof(a) / sizeof(a[0]);
cout << countPairs(a, n, k) << endl;
return 0;
}
// java code to find count of Pairs with
// difference less than K.
import java.io.*;
class GFG {
static int countPairs(int a[], int n, int k)
{
int res = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (Math.abs(a[j] - a[i]) < k)
res++;
return res;
}
// Driver code
public static void main (String[] args)
{
int a[] = {1, 10, 4, 2};
int k = 3;
int n = a.length;
System.out.println(countPairs(a, n, k));
}
}
// This code is contributed by vt_m.
# Python3 code to find count of Pairs
# with difference less than K.
def countPairs(a, n, k):
res = 0
for i in range(n):
for j in range(i + 1, n):
if (abs(a[j] - a[i]) < k):
res += 1
return res
# Driver code
a = [1, 10, 4, 2]
k = 3
n = len(a)
print(countPairs(a, n, k), end = "")
# This code is contributed by Azkia Anam.
// C# code to find count of Pairs
// with difference less than K.
using System;
class GFG {
// Function to count pairs
static int countPairs(int []a, int n,
int k)
{
int res = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (Math.Abs(a[j] - a[i]) < k)
res++;
return res;
}
// Driver code
public static void Main ()
{
int []a = {1, 10, 4, 2};
int k = 3;
int n = a.Length;
Console.WriteLine(countPairs(a, n, k));
}
}
// This code is contributed by vt_m.
<?php
// PHP code to find count of Pairs
// with difference less than K.
function countPairs( $a, $n, $k)
{
$res = 0;
for($i = 0; $i < $n; $i++)
for($j = $i + 1; $j < $n; $j++)
if (abs($a[$j] - $a[$i]) < $k)
$res++;
return $res;
}
// Driver code
$a = array(1, 10, 4, 2);
$k = 3;
$n = count($a);
echo countPairs($a, $n, $k);
// This code is contributed by anuj_67.
?>
<script>
// Javascript code to find count of Pairs
// with difference less than K.
function countPairs(a, n, k)
{
var res = 0;
for(var i = 0; i < n; i++)
for(var j = i + 1; j < n; j++)
if (Math.abs(a[j] - a[i]) < k)
res++;
return res;
}
// Driver code
var a = [ 1, 10, 4, 2 ];
var k = 3;
var n = a.length;
document.write(countPairs(a, n, k));
// This code is contributed by bunnyram19
</script>
Output
2
Time Complexity: O(n2)
Auxiliary Space: O(1)
Method 2 (Sorting): First we sort the array. Then we start from the first element and keep considering pairs while the difference is less than k. If we stop the loop when we find a difference more than or equal to k and move to the next element.
Implementation:
// C++ code to find count of Pairs with
// difference less than K.
#include <bits/stdc++.h>
using namespace std;
int countPairs(int a[], int n, int k)
{
// to sort the array.
sort(a, a + n);
int res = 0;
for (int i = 0; i < n; i++) {
// Keep incrementing result while
// subsequent elements are within
// limits.
int j = i+1;
while (j < n && a[j] - a[i] < k) {
res++;
j++;
}
}
return res;
}
// Driver code
int main()
{
int a[] = {1, 10, 4, 2};
int k = 3;
int n = sizeof(a) / sizeof(a[0]);
cout << countPairs(a, n, k) << endl;
return 0;
}
// Java code to find count of Pairs with
// difference less than K.
import java.io.*;
import java.util.Arrays;
class GFG
{
static int countPairs(int a[], int n, int k)
{
// to sort the array.
Arrays.sort(a);
int res = 0;
for (int i = 0; i < n; i++)
{
// Keep incrementing result while
// subsequent elements are within
// limits.
int j = i + 1;
while (j < n && a[j] - a[i] < k)
{
res++;
j++;
}
}
return res;
}
// Driver code
public static void main (String[] args)
{
int a[] = {1, 10, 4, 2};
int k = 3;
int n = a.length;
System.out.println(countPairs(a, n, k));
}
}
// This code is contributed by vt_m.
# Python code to find count of Pairs
# with difference less than K.
def countPairs(a, n, k):
# to sort the array
a.sort()
res = 0
for i in range(n):
# Keep incrementing result while
# subsequent elements are within limits.
j = i+1
while (j < n and a[j] - a[i] < k):
res += 1
j += 1
return res
# Driver code
a = [1, 10, 4, 2]
k = 3
n = len(a)
print(countPairs(a, n, k), end = "")
# This code is contributed by Azkia Anam.
// C# code to find count of Pairs
// with difference less than K.
using System;
class GFG {
// Function to count pairs
static int countPairs(int []a, int n,
int k)
{
// to sort the array.
Array.Sort(a);
int res = 0;
for (int i = 0; i < n; i++)
{
// Keep incrementing result while
// subsequent elements are within
// limits.
int j = i + 1;
while (j < n && a[j] - a[i] < k)
{
res++;
j++;
}
}
return res;
}
// Driver code
public static void Main ()
{
int []a = {1, 10, 4, 2};
int k = 3;
int n = a.Length;
Console.WriteLine(countPairs(a, n, k));
}
}
// This code is contributed by vt_m.
<?php
// PHP code to find count of
// Pairs with difference less than K.
function countPairs( $a, $n, $k)
{
// to sort the array.
sort($a);
$res = 0;
for ( $i = 0; $i < $n; $i++)
{
// Keep incrementing result
// while subsequent elements
// are within limits.
$j = $i + 1;
while ($j < $n and
$a[$j] - $a[$i] < $k)
{
$res++;
$j++;
}
}
return $res;
}
// Driver code
$a = array(1, 10, 4, 2);
$k = 3;
$n = count($a);
echo countPairs($a, $n, $k);
// This code is contributed by anuj_67.
?>
<script>
// JavaScript code to find count of Pairs with
// difference less than K.
function countPairs(a, n, k)
{
// To sort the array.
a.sort((a, b) => a - b);
let res = 0;
for(let i = 0; i < n; i++)
{
// Keep incrementing result while
// subsequent elements are within
// limits.
let j = i + 1;
while (j < n && a[j] - a[i] < k)
{
res++;
j++;
}
}
return res;
}
// Driver code
let a = [ 1, 10, 4, 2 ];
let k = 3;
let n = a.length;
document.write(countPairs(a, n, k) + "<br>");
// This code is contributed by Surbhi Tyagi.
</script>
Output
2
Time Complexity: O(res) where res is the number of pairs in output. Note that in the worst case this also takes O(n2) time but works much better in general.
Space Complexity: O(1) as no extra space has been used.
Method 3 (Using lower_bound):
The problem can be efficiently solved using the lower_bound function in O(n*log(n)) time complexity.
The idea is to first sort the elements of the array and then for each element a[i], we will find all such elements which are on the right side of a[i] and whose difference with a[i] is less than k. This can be evaluated by searching for all elements which have a value less than a[i]+k. And this can be easily evaluated with the help of the lower_bound function in O(log(n)) time for each element.
Illustrative example:
Given: a[] = {1, 10, 4, 2} and k=3
Array after sorting: a[] = {1, 2, 4, 10}
For 1, all elements on right side of 1 which are less than 1+3=4 -> {2}
For 2, all elements on right side of 2 which are less than 2+3=5 -> {4}
For 4, all elements on right side of 4 which are less than 4+3=7 -> {}
For 10, all elements on right side of 10 which are less than 10+3=13 -> {}
So total 2 such elements we found, hence answer = 2.
Approach:
- Sort the given array.
- Iterate through each element and store a[i]+k in val for index i.
- Then using the lower_bound function we will find the index of the first occurrence of elements which is greater than or equal to val.
- After this, we will add the count of all pairs for a[i] by finding the difference between the index which is found using the lower bound function and current index i.
Below is the implementation of the above approach.
// C++ code to find count of Pairs with
// difference less than K.
#include <bits/stdc++.h>
using namespace std;
int countPairs(int a[], int n, int k)
{
// to sort the array.
sort(a, a + n);
int res = 0;
// iterating through each index
for (int i = 0; i < n; i++) {
// here val stores the value till
// which the number should be possible
// so that its difference with a[i]
// is less than k.
int val = a[i] + k;
// finding the first occurrence of
// element in array which is greater than
// or equal to val.
int y = lower_bound(a, a + n, val) - a;
// adding the count of all pairs
// possible for current a[i]
res += (y - i - 1);
}
return res;
}
// Driver code
int main()
{
int a[] = { 1, 10, 4, 2 };
int k = 3;
int n = sizeof(a) / sizeof(a[0]);
cout << countPairs(a, n, k) << endl;
return 0;
}
// This code is contributed by Pushpesh raj
/*package whatever //do not write package name here */
import java.util.*;
import java.io.*;
class GFG {
public static int countPairs(int[] a, int n, int k) {
// to sort the array
Arrays.sort(a);
int res = 0;
// iterating through each index
for (int i = 0; i < n; i++) {
// here val stores the value till
// which the number should be possible
// so that its difference with a[i]
// is less than k.
int val = a[i] + k;
// finding the first occurrence of
// element in array which is greater than
// or equal to val.
int y = Arrays.binarySearch(a, val);
if (y < 0) {
y = -(y + 1);
}
// adding the count of all pairs
// possible for current a[i]
res += (y - i - 1);
}
return res;
}
// Driver code
public static void main(String[] args) {
int[] a = {1, 10, 4, 2};
int k = 3;
int n = a.length;
System.out.println(countPairs(a, n, k));
}
}
using System;
public class GFG
{
public static int CountPairsWithDiffLessThanK(int[] a, int n, int k)
{
// to sort the array.
Array.Sort(a);
int res = 0;
// iterating through each index
for (int i = 0; i < n; i++)
{
// here val stores the value till
// which the number should be possible
// so that its difference with a[i]
// is less than k.
int val = a[i] + k;
// finding the first occurrence of
// element in array which is greater than
// or equal to val.
int y = Array.BinarySearch(a, val);
if (y < 0)
{
y = ~y;
}
// adding the count of all pairs
// possible for current a[i]
res += (y - i - 1);
}
return res;
}
// Driver code
public static void Main()
{
int[] a = { 1, 10, 4, 2 };
int k = 3;
int n = a.Length;
Console.WriteLine(CountPairsWithDiffLessThanK(a, n, k));
}
}
import bisect
def count_pairs(a, n, k):
# to sort the array.
a.sort()
res = 0
# iterating through each index
for i in range(n):
# here val stores the value till
# which the number should be possible
# so that its difference with a[i]
# is less than k.
val = a[i] + k
# finding the first occurrence of
# element in array which is greater than
# or equal to val.
y = bisect.bisect_left(a, val)
# adding the count of all pairs
# possible for current a[i]
res += (y - i - 1)
return res
# Driver code
a = [1, 10, 4, 2]
k = 3
n = len(a)
print(count_pairs(a, n, k))
function count_pairs(a, n, k) {
// to sort the array.
a.sort(function(a, b){return a - b});
var res = 0;
// iterating through each index
for (var i = 0; i < n; i++) {
// here val stores the value till
// which the number should be possible
// so that its difference with a[i]
// is less than k.
var val = a[i] + k;
// finding the first occurrence of
// element in array which is greater than
// or equal to val.
var y = a.findIndex(function(x) {return x >= val});
// adding the count of all pairs
// possible for current a[i]
res += (y - i - 1) >= 0 ? (y - i - 1) : 0;
}
return res;
}
// Driver code
var a = [1, 10, 4, 2];
var k = 3;
var n = a.length;
console.log(count_pairs(a, n, k));
Output
2
Time complexity: O(n*log(n))
Auxiliary Space: O(1)
If you like GeeksforGeeks and write.geeksforgeeks.org">write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org.