Skip to content
Related Articles

Related Articles

Improve Article
Count of pairs with difference at most K with no element repeating
  • Difficulty Level : Medium
  • Last Updated : 31 May, 2021

Given an array arr[] and a number K, the task is to count the number of pairs whose difference is less than or equal to the K, such that an element can only be considered in only one pair. 

Examples: 

Input: arr[] = {1, 3, 3, 9, 4}, K = 2 
Output:
Explanation: 
There are only two pairs whose difference is atmost 2 
(1, 3), (3, 4)

Input: arr[] = {1, 4, 3, 7, 5}, K = 2 
Output:
Explanation: 
There are five pairs in the array whose difference is atmost 2, 
(1, 3), (3, 4), (4, 5), (3, 5), (5, 7) 
But only two of them can be considered at a time because one element 
can be taken in a pair only once. 
 



 

Approach: 
The idea is to sort the array and find the difference of the adjacent elements, If the difference is at most K, then the pair is considered and the count is increased and then, as per the condition, any element can be in only one pair, then if a pair is found, the increment the counter by 2 such that any element is present in only one pair.

For Example: 

Given Array - {1, 4, 3, 7, 5}, K = 2 
After Sorting Array will be - {1, 3, 4, 5, 7}
Step 1 - i = 0, count = 0
Consider the pair of elements for i and i + 1
Pair - (1, 3), Difference = 3 - 1 = 2
As the Difference is less than equal to 2
count = 1 and i = 2

Step 2 - i = 2, count = 1
Consider the pair of elements for i and i + 1
Pair - (4, 5), Difference = 5 - 4 = 1
As the Difference is less than equal to 2
count = 2 and i = 4
As i is greater than length-2,
there will be no more possible pairs.

Algorithm:  

  • Sort the array using any sorting algorithm such that consecutive elements are together.
  • Initialize the index counter (say i) to zero and run a while loop till the index counter is less than (length – 1) 
    1. Check the difference of the elements at index i and i + 1.
    2. If the difference is less than or equal to K increment the index by 2 and also increment the counter by 1 to consider increase the elements increase at once.
    3. Else, increment the index by 1 to consider the pair formed by the next element.

Below is the implementation of the above approach:

C++




// C++ implementation to count the
// number of pairs whose difference
// is atmost K in an array
#include <iostream>
#include<bits/stdc++.h>
 
using namespace std;
 
    // Function to count the
    // number of pairs whose difference
    // is atmost K in an array
    int countPairs(int arr[], int k, int n)
    {
         
        // Variable to store the count of pairs
        // whose difference is atmost K
        int pair = 0;
        int index = 0;
         
        //int n = sizeof(arr)/sizeof(arr[0]);
         
        // Sorting the Array
        sort(arr,arr + n) ;
                 
        // Loop to consider the consecutive
        // pairs of the array
        while(index < n -1)
        {
             
            // if Pair found increment
            // the index by 2
            if (arr[index + 1] - arr[index] <= k){
                pair += 1 ;
                index += 2 ;
            }
            else{
                index += 1;
            }
        }
        return pair ;
     
    }
     
// Driver Code
int main() {
    int arr[] = {1, 4, 3, 7, 5} ;
    int k = 2;
     
     int n = sizeof(arr)/sizeof(arr[0]);
    // Function Call
    int count = countPairs(arr, k,n) ;
    cout << count << endl;;
}
 
// This code is contributed by AnkitRai01

Java




// Java implementation to count the
// number of pairs whose difference
// is atmost K in an array
import java.util.*;
 
class GFG
{
 
    // Function to count the
    // number of pairs whose difference
    // is atmost K in an array
    static int countPairs(int arr[], int k)
    {
         
        // Sorting the Array
        Arrays.sort(arr) ;
         
        // Variable to store the count of pairs
        // whose difference is atmost K
        int pair = 0;
        int index = 0;
         
        // Loop to consider the consecutive
        // pairs of the array
        while(index < arr.length -1)
        {
             
            // if Pair found increment
            // the index by 2
            if (arr[index + 1] - arr[index] <= k){
                pair += 1 ;
                index += 2 ;
            }
            else{
                index += 1;
            }
        }
        return pair ;
     
    }
     
    // Driver Code
    public static void main (String[] args) {
        int arr[] = {1, 4, 3, 7, 5} ;
        int k = 2;
         
        // Function Call
        int count = countPairs(arr, k) ;
        System.out.println(count);
    }
}
 
// This code is contributed by AnkitRai01

Python3




# Python3 implementation to count the
# number of pairs whose difference
# is atmost K in an array
 
 
# Function to count the
# number of pairs whose difference
# is atmost K in an array
def countPairs(arr, k):
     
    # Sorting the Array
    arr.sort()
     
    # Variable to store the count of pairs
    # whose difference is atmost K
    pair = 0
    index = 0
     
    # Loop to consider the consecutive
    # pairs of the array
    while(index < len(arr)-1):
         
        # if Pair found increment
        # the index by 2
        if arr[index + 1] - arr[index] <= k:
            pair += 1
            index += 2
        else:
            index += 1
             
    return pair
 
# Driver Code
if __name__ == "__main__":
    arr = [1, 4, 3, 7, 5]
    k = 2
    # Function Call
    count = countPairs(arr, k)
    print(count)

C#




// C# implementation to count the
// number of pairs whose difference
// is atmost K in an array
using System;
 
class GFG
{
 
    // Function to count the
    // number of pairs whose difference
    // is atmost K in an array
    static int countPairs(int []arr, int k)
    {
         
        // Sorting the Array
        Array.Sort(arr) ;
         
        // Variable to store the count of pairs
        // whose difference is atmost K
        int pair = 0;
        int index = 0;
         
        // Loop to consider the consecutive
        // pairs of the array
        while(index < arr.Length - 1)
        {
             
            // if Pair found increment
            // the index by 2
            if (arr[index + 1] - arr[index] <= k)
            {
                pair += 1 ;
                index += 2 ;
            }
            else
            {
                index += 1;
            }
        }
        return pair ;
    }
     
    // Driver Code
    public static void Main ()
    {
        int []arr = {1, 4, 3, 7, 5} ;
        int k = 2;
         
        // Function Call
        int count = countPairs(arr, k) ;
        Console.WriteLine(count);
    }
}
 
// This code is contributed by AnkitRai01

Javascript




<script>
    // Javascript implementation to count the
    // number of pairs whose difference
    // is atmost K in an array
 
 
    // Function to count the
    // number of pairs whose difference
    // is atmost K in an array
    function countPairs(arr, k, n)
    {
         
        // Variable to store the count of pairs
        // whose difference is atmost K
        let pair = 0;
        let index = 0;
         
        //int n = sizeof(arr)/sizeof(arr[0]);
         
        // Sorting the Array
        arr.sort((a, b) => a - b) ;
                 
        // Loop to consider the consecutive
        // pairs of the array
        while(index < n -1)
        {
             
            // if Pair found increment
            // the index by 2
            if (arr[index + 1] - arr[index] <= k){
                pair += 1 ;
                index += 2 ;
            }
            else{
                index += 1;
            }
        }
        return pair ;
     
    }
     
// Driver Code
 
let arr = [1, 4, 3, 7, 5];
let k = 2;
     
let n = arr.length;
 
// Function Call
let count = countPairs(arr, k,n);
 
document.write(count + "<br>");
 
// This code is contributed by _saurabh_jaiswal
</script>
Output: 
2

 

Performance Analysis: 

  • Time Complexity: In the above-given approach, there is sorting of the array which takes O(N logN), and also there is also one iteration to count the number of pairs which is O(N). 
    Hence, the overall complexity of the approach is O(N logN + N).
  • Space Complexity: In the above-given approach, there is no extra space. Hence, the overall space complexity of the approach will be O(1)

 

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :