Find k ordered pairs in array with minimum difference d

Given an array arr[] and two integers K and D, the task is to find exactly K pairs (arr[i], arr[j]) from the array such that |arr[i] – arr[j]| ≥ D and i != j. If it is impossible to get such pairs then print -1. Note that a single element can only participate in a single pair.

Examples:

Input: arr[] = {4, 6, 10, 23, 14, 7, 2, 20, 9}, K = 4, D = 3
Output:
(2, 10)
(4, 14)
(6, 20)
(7, 23)

Input: arr[] = {2, 10, 4, 6, 12, 5, 7, 3, 1, 9}, K = 5, D = 10
Output : -1

Approach: If we had to find only 1 pair then we would have checked only the maximum and minimum element from the array. Similarly, to get K pairs we can compare minimum K elements with the corresponding maximum K elements. Sorting can be used to get the minimum and maximum elements.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the required pairs
void findPairs(int arr[], int n, int k, int d)
{
  
    // There has to be atleast 2*k elements
    if (n < 2 * k) {
        cout << -1;
        return;
    }
  
    // To store the pairs
    vector<pair<int, int> > pairs;
  
    // Sort the given array
    sort(arr, arr + n);
  
    // For every possible pair
    for (int i = 0; i < k; i++) {
  
        // If the current pair is valid
        if (arr[n - k + i] - arr[i] >= d) {
  
            // Insert it into the pair vector
            pair<int, int> p = make_pair(arr[i], arr[n - k + i]);
            pairs.push_back(p);
        }
    }
  
    // If k pairs are not possible
    if (pairs.size() < k) {
        cout << -1;
        return;
    }
  
    // Print the pairs
    for (auto v : pairs) {
        cout << "(" << v.first << ", "
             << v.second << ")" << endl;
    }
}
  
// Driver code
int main()
{
    int arr[] = { 4, 6, 10, 23, 14, 7, 2, 20, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 4, d = 3;
  
    findPairs(arr, n, k, d);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
  
class GFG
{
    static class pair 
    
        int first, second; 
        public pair(int first, int second) 
        
            this.first = first; 
            this.second = second; 
        
    }
  
    // Function to find the required pairs
    static void findPairs(int arr[], int n,
                          int k, int d)
    {
  
        // There has to be atleast 2*k elements
        if (n < 2 * k)
        {
            System.out.print(-1);
            return;
        }
  
        // To store the pairs
        Vector<pair> pairs = new Vector<pair>();
  
        // Sort the given array
        Arrays.sort(arr);
  
        // For every possible pair
        for (int i = 0; i < k; i++) 
        {
  
            // If the current pair is valid
            if (arr[n - k + i] - arr[i] >= d) 
            {
  
                // Insert it into the pair vector
                pair p = new pair(arr[i], 
                                  arr[n - k + i]);
                pairs.add(p);
            }
        }
  
        // If k pairs are not possible
        if (pairs.size() < k) 
        {
            System.out.print(-1);
            return;
        }
  
        // Print the pairs
        for (pair v : pairs)
        {
            System.out.println("(" + v.first + 
                               ", " + v.second + ")");
        }
    }
  
    // Driver code
    public static void main(String[] args) 
    {
        int arr[] = { 4, 6, 10, 23, 14, 7, 2, 20, 9 };
        int n = arr.length;
        int k = 4, d = 3;
      
        findPairs(arr, n, k, d);
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach
  
# Function to find the required pairs
def findPairs(arr, n, k, d):
  
    # There has to be atleast 2*k elements
    if (n < 2 * k):
        print("-1")
        return
  
    # To store the pairs
    pairs=[]
  
    # Sort the given array
    arr=sorted(arr)
  
    # For every possible pair
    for i in range(k):
  
        # If the current pair is valid
        if (arr[n - k + i] - arr[i] >= d):
  
            # Insert it into the pair vector
            pairs.append([arr[i], arr[n - k + i]])
  
  
    # If k pairs are not possible
    if (len(pairs) < k):
        print("-1")
        return
  
    # Prthe pairs
    for v in pairs:
        print("(",v[0],", ",v[1],")")
  
# Driver code
  
arr = [4, 6, 10, 23, 14, 7, 2, 20, 9]
n = len(arr)
k = 4
d = 3
  
findPairs(arr, n, k, d)
  
# This code is contributed by mohit kumar 29

chevron_right


C#

// C# implementation of the approach
using System;
using System.Collections.Generic;

class GFG
{
public class pair
{
public int first, second;
public pair(int first, int second)
{
this.first = first;
this.second = second;
}
}

// Function to find the required pairs
static void findPairs(int []arr, int n,
int k, int d)
{

// There has to be atleast 2*k elements
if (n < 2 * k) { Console.Write(-1); return; } // To store the pairs List pairs = new List();

// Sort the given array
Array.Sort(arr);

// For every possible pair
for (int i = 0; i < k; i++) { // If the current pair is valid if (arr[n - k + i] - arr[i] >= d)
{

// Insert it into the pair vector
pair p = new pair(arr[i],
arr[n – k + i]);
pairs.Add(p);
}
}

// If k pairs are not possible
if (pairs.Count < k) { Console.Write(-1); return; } // Print the pairs foreach (pair v in pairs) { Console.WriteLine ("(" + v.first + ", " + v.second + ")"); } } // Driver code public static void Main(String[] args) { int []arr = { 4, 6, 10, 23, 14, 7, 2, 20, 9 }; int n = arr.Length; int k = 4, d = 3; findPairs(arr, n, k, d); } } // This code is contributed by PrinciRaj1992 [tabbyending]

Output:

(2, 10)
(4, 14)
(6, 20)
(7, 23)


My Personal Notes arrow_drop_up

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 :
Practice Tags :


Be the First to upvote.


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