Count all disjoint pairs having absolute difference at least K from a given array

Given an array arr[] consisting of N integers, the task is to count all disjoint pairs having absolute difference at least K
Note: The pair (arr[i], arr[j]) and (arr[j], arr[i]) are considered as the same pair.

Examples:

Input: arr[] = {1, 3, 3, 5}, K = 2
Output: 2
Explanation:
The following two pairs satisfy the necessary conditions: 

  • {arr[0], arr[1]} = (1, 3) whose absolute difference is |1 – 3| = 2
  • {arr[2], arr[3]} = (3, 5) whose absolute difference is |3 – 5| = 2

Input: arr[] = {1, 2, 3, 4}, K = 3
Output: 1
Explanation:
The only pair satisfying the necessary conditions is {arr[0], arr[3]} = (1, 4), since |1 – 4| = 3.

Naive Approach: The simplest approach is to generate all possible pairs of the given array and count those pairs whose absolute difference is at least K and to keep track of elements that have already been taken into pairs, using an auxiliary array visited[] to mark the paired elements.



Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count distinct pairs
// with absolute difference atleast K
void countPairsWithDiffK(int arr[],
                         int N, int K)
{
    // Track the element that
    // have been paired
    int vis[N];
    memset(vis, 0, sizeof(vis));
 
    // Stores count of distinct pairs
    int count = 0;
 
    // Pick all elements one by one
    for (int i = 0; i < N; i++) {
 
        // If already visited
        if (vis[i] == 1)
            continue;
 
        for (int j = i + 1; j < N; j++) {
 
            // If already visited
            if (vis[j] == 1)
                continue;
 
            // If difference is at least K
            if (abs(arr[i] - arr[j]) >= K) {
 
                // Mark element as visited and
                // increment the count
                count++;
                vis[i] = 1;
                vis[j] = 1;
                break;
            }
        }
    }
 
    // Print the final count
    cout << count << ' ';
}
 
// Driver Code
int main()
{
    // Given arr[]
    int arr[] = { 1, 3, 3, 5 };
 
    // Size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Given difference K
    int K = 2;
 
    // Function Call
    countPairsWithDiffK(arr, N, K);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG{
  
// Function to count distinct pairs
// with absolute difference atleast K
static void countPairsWithDiffK(int arr[],
                                int N, int K)
{
     
    // Track the element that
    // have been paired
    int []vis = new int[N];
    Arrays.fill(vis, 0);
     
    // Stores count of distinct pairs
    int count = 0;
 
    // Pick all elements one by one
    for(int i = 0; i < N; i++)
    {
         
        // If already visited
        if (vis[i] == 1)
            continue;
 
        for(int j = i + 1; j < N; j++)
        {
             
            // If already visited
            if (vis[j] == 1)
                continue;
 
            // If difference is at least K
            if (Math.abs(arr[i] - arr[j]) >= K)
            {
                 
                // Mark element as visited and
                // increment the count
                count++;
                vis[i] = 1;
                vis[j] = 1;
                break;
            }
        }
    }
 
    // Print the final count
    System.out.print(count);
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given arr[]
    int arr[] = { 1, 3, 3, 5 };
 
    // Size of array
    int N = arr.length;
 
    // Given difference K
    int K = 2;
 
    // Function Call
    countPairsWithDiffK(arr, N, K);
}
}
 
// This code is contributed by bgangwar59
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to count distinct pairs
# with absolute difference atleast K
def countPairsWithDiffK(arr, N, K):
     
    # Track the element that
    # have been paired
    vis = [0] * N
     
    # Stores count of distinct pairs
    count = 0
 
    # Pick all elements one by one
    for i in range(N):
         
        # If already visited
        if (vis[i] == 1):
            continue
 
        for j in range(i + 1, N):
             
            # If already visited
            if (vis[j] == 1):
                continue
 
            # If difference is at least K
            if (abs(arr[i] - arr[j]) >= K):
 
                # Mark element as visited and
                # increment the count
                count += 1
                vis[i] = 1
                vis[j] = 1
                break
 
    # Print the final count
    print(count)
 
# Driver Code
if __name__ == '__main__':
     
    # Given arr[]
    arr = [ 1, 3, 3, 5 ]
 
    # Size of array
    N = len(arr)
     
    # Given difference K
    K = 2
 
    # Function Call
    countPairsWithDiffK(arr, N, K)
 
# This code is contributed by mohit kumar 29
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
 
class GFG{
 
// Function to count distinct pairs
// with absolute difference atleast K
static void countPairsWithDiffK(int[] arr, int N,
                                int K)
{
     
    // Track the element that
    // have been paired
    int[] vis = new int[N];
 
    // Stores count of distinct pairs
    int count = 0;
 
    // Pick all elements one by one
    for(int i = 0; i < N; i++)
    {
         
        // If already visited
        if (vis[i] == 1)
            continue;
             
        for(int j = i + 1; j < N; j++)
        {
             
            // If already visited
            if (vis[j] == 1)
                continue;
 
            // If difference is at least K
            if (Math.Abs(arr[i] - arr[j]) >= K)
            {
                 
                // Mark element as visited and
                // increment the count
                count++;
                vis[i] = 1;
                vis[j] = 1;
                break;
            }
        }
    }
 
    // Print the final count
    Console.Write(count);
}
 
// Driver Code
public static void Main()
{
     
    // Given arr[]
    int[] arr = { 1, 3, 3, 5 };
 
    // Size of array
    int N = arr.Length;
 
    // Given difference K
    int K = 2;
 
    // Function Call
    countPairsWithDiffK(arr, N, K);
}
}
 
// This code is contributed by chitranayal
chevron_right

Output
2 

Time Complexity: O(N2)
Auxiliary Space: O(N)

Efficient Approach: The efficient idea is to use Binary Search to find the first occurrence having a difference of at least K. Below are the steps:

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if it is possible to
// form M pairs with abs diff at least K
bool isValid(int arr[], int n, int m,
             int d)
{
    // Traverse the array over [0, M]
    for (int i = 0; i < m; i++) {
 
        // If valid index
        if (abs(arr[n - m + i]
                - arr[i])
            < d) {
            return 0;
        }
    }
 
    // Return 1
    return 1;
}
 
// Function to count distinct pairs
// with absolute difference atleasr K
int countPairs(int arr[], int N, int K)
{
    // Stores the count of all
    // possible pairs
    int ans = 0;
 
    // Initialize left and right
    int left = 0, right = N / 2 + 1;
 
    // Sort the array
    sort(arr, arr + N);
 
    // Perform Binary Search
    while (left < right) {
 
        // Find the value of mid
        int mid = (left + right) / 2;
 
        // Check valid index
        if (isValid(arr, N, mid, K)) {
 
            // Update ans
            ans = mid;
            left = mid + 1;
        }
        else
            right = mid - 1;
    }
 
    // Print the answer
    cout << ans << ' ';
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 3, 3, 5 };
 
    // Given difference K
    int K = 2;
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    countPairs(arr, N, K);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG{
  
// Function to check if it is possible to
// form M pairs with abs diff at least K
static int isValid(int arr[], int n, int m,
                   int d)
{
     
    // Traverse the array over [0, M]
    for(int i = 0; i < m; i++)
    {
         
        // If valid index
        if (Math.abs(arr[n - m + i] - arr[i]) < d)
        {
            return 0;
        }
    }
 
    // Return 1
    return 1;
}
 
// Function to count distinct pairs
// with absolute difference atleasr K
static void countPairs(int arr[], int N, int K)
{
     
    // Stores the count of all
    // possible pairs
    int ans = 0;
 
    // Initialize left and right
    int left = 0, right = N / 2 + 1;
 
    // Sort the array
    Arrays.sort(arr);
 
    // Perform Binary Search
    while (left < right)
    {
         
        // Find the value of mid
        int mid = (left + right) / 2;
 
        // Check valid index
        if (isValid(arr, N, mid, K) == 1)
        {
             
            // Update ans
            ans = mid;
            left = mid + 1;
        }
        else
            right = mid - 1;
    }
 
    // Print the answer
    System.out.print(ans);
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given array arr[]
    int arr[] = { 1, 3, 3, 5 };
 
    // Given difference K
    int K = 2;
 
    // Size of the array
    int N = arr.length;
 
    // Function call
    countPairs(arr, N, K);
}
}
 
// This code is contributed by bgangwar59
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to check if it is possible to
# form M pairs with abs diff at least K
def isValid(arr, n, m, d):
     
    # Traverse the array over [0, M]
    for i in range(m):
         
        # If valid index
        if (abs(arr[n - m + i] - arr[i]) < d):
            return 0
 
    # Return 1
    return 1
 
# Function to count distinct pairs
# with absolute difference atleasr K
def countPairs(arr, N, K):
     
    # Stores the count of all
    # possible pairs
    ans = 0
 
    # Initialize left and right
    left = 0
    right = N // 2 + 1
 
    # Sort the array
    arr.sort(reverse = False)
 
    # Perform Binary Search
    while (left < right):
         
        # Find the value of mid
        mid = (left + right) // 2
 
        # Check valid index
        if (isValid(arr, N, mid, K)):
             
            # Update ans
            ans = mid
            left = mid + 1
        else:
            right = mid - 1
 
    # Print the answer
    print(ans, end = "")
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr[]
    arr = [ 1, 3, 3, 5 ]
 
    # Given difference K
    K = 2
 
    # Size of the array
    N = len(arr)
 
    # Function call
    countPairs(arr, N, K)
 
# This code is contributed by bgangwar59
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the
// above approach
using System;
class GFG{
  
// Function to check if it
// is possible to form M
// pairs with abs diff at
// least K
static int isValid(int []arr, int n,
                   int m, int d)
{   
  // Traverse the array over
  // [0, M]
  for(int i = 0; i < m; i++)
  {
    // If valid index
    if (Math.Abs(arr[n - m + i] -
                 arr[i]) < d)
    {
      return 0;
    }
  }
 
  // Return 1
  return 1;
}
 
// Function to count distinct
// pairs with absolute difference
// atleast K
static void countPairs(int []arr,
                       int N, int K)
{   
  // Stores the count of all
  // possible pairs
  int ans = 0;
 
  // Initialize left
  // and right
  int left = 0,
      right = N / 2 + 1;
 
  // Sort the array
  Array.Sort(arr);
 
  // Perform Binary Search
  while (left < right)
  {
    // Find the value of mid
    int mid = (left +
               right) / 2;
 
    // Check valid index
    if (isValid(arr, N,
                mid, K) == 1)
    {
      // Update ans
      ans = mid;
      left = mid + 1;
    }
    else
      right = mid - 1;
  }
 
  // Print the answer
  Console.WriteLine(ans);
}
 
// Driver Code
public static void Main()
{   
  // Given array arr[]
  int []arr = {1, 3, 3, 5};
 
  // Given difference K
  int K = 2;
 
  // Size of the array
  int N = arr.Length;
 
  // Function call
  countPairs(arr, N, K);
}
}
 
// This code is contributed by surendra_gangwar
chevron_right

Output
2 

Time Complexity: O(N*log N)
Auxiliary Space: 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.




Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using 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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :