Pairs with Difference less than K

Given an array of n integers, We need to find all pairs with 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 difference is within limits or not.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.
?>

chevron_right



Output :

  2

Time Complexity : O(n2)
Auxiliary Space : O(1)

Method 2 (Sorting) : First we sort the array. Then we start from first element and keep considering pairs while difference is less than k. If we stop the loop when we find difference more than or equal to k and move to next element.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
{
    // 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.
?>

chevron_right



Output :

  2

Time complexity : O(res) where res is number of pairs in output. Note that in worst case this also takes O(n2) time but works much better in general.

This article is contributed by Harsha Mogali. If you like GeeksforGeeks and contribute.geeksforgeeks.org”>contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : vt_m



Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.