Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
C++ Program to Find a pair with the given difference
Next article icon

Find k ordered pairs in array with minimum difference d

Last Updated : 23 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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++




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

Java




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

Python3




# 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
 
    # Print the 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
 
 

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<pair> pairs = new List<pair>();
 
        // 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
 
 

Javascript




<script>
 
// JavaScript implementation of the approach
 
// Function to find the required pairs
function findPairs(arr, n, k, d) {
 
    // There has to be atleast 2*k elements
    if (n < 2 * k) {
        document.write(-1);
        return;
    }
 
    // To store the pairs
    let pairs = [];
 
    // Sort the given array
    arr.sort((a, b) => a - b);
 
    // For every possible pair
    for (let 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
            let p = [arr[i], arr[n - k + i]];
            pairs.push(p);
        }
    }
 
    // If k pairs are not possible
    if (pairs.length < k) {
        document.write(-1);
        return;
    }
 
    // Print the pairs
    for (let v of pairs) {
        document.write("(" + v[0] + ", " + v[1] + ")" + "<br>");
    }
}
 
// Driver code
 
let arr = [4, 6, 10, 23, 14, 7, 2, 20, 9];
let n = arr.length;
let k = 4, d = 3;
 
findPairs(arr, n, k, d);
 
 
// This code is contributed by gfgking
 
</script>
 
 
Output: 
(2, 10) (4, 14) (6, 20) (7, 23)

 

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)



Next Article
C++ Program to Find a pair with the given difference

S

sidhhantB
Improve
Article Tags :
  • Algorithms
  • Arrays
  • C++ Programs
  • Competitive Programming
  • DSA
  • Sorting
  • cpp-pair
  • cpp-vector
Practice Tags :
  • Algorithms
  • Arrays
  • Sorting

Similar Reads

  • C++ Program to Find a pair with the given difference
    Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78 Output: Pair Found: (2, 80) Input: arr[] = {90, 70, 20, 80, 50}, n = 45 Output: No Such Pair Recommended: Please solve it on "PRA
    4 min read
  • Count pairs from an array with absolute difference not less than the minimum element in the pair
    Given an array arr[] consisting of N positive integers, the task is to find the number of pairs (arr[i], arr[j]) such that absolute difference between the two elements is at least equal to the minimum element in the pair. Examples: Input: arr[] = {1, 2, 2, 3}Output: 3Explanation:Following are the pa
    14 min read
  • C++ Program to Find closest number in array
    Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples: Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11 Output : 9 9 is closest to 11 in given array Input :arr[] = {2, 5, 6, 7, 8, 8, 9};
    4 min read
  • Find the Kth pair in ordered list of all possible sorted pairs of the Array
    Given an array arr[] containing N integers and a number K, the task is to find the K-th pair in the ordered list of all possible N2 sorted pairs of the array arr[]. A pair (p1, q1) is lexicographically smaller than the pair (p2, q2) only if p1 ? p2 and q1 < q2. Examples: Input: arr[] = {2, 1}, K
    6 min read
  • Print distinct absolute differences of all possible pairs from a given array
    Given an array, arr[] of size N, the task is to find the distinct absolute differences of all possible pairs of the given array. Examples: Input: arr[] = { 1, 3, 6 } Output: 2 3 5 Explanation: abs(arr[0] - arr[1]) = 2 abs(arr[1] - arr[2]) = 3 abs(arr[0] - arr[2]) = 5 Input: arr[] = { 5, 6, 7, 8, 14,
    9 min read
  • C++ Program for Find k pairs with smallest sums in two arrays
    Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples: Input : arr1[] = {1, 7, 11} arr2[] = {2, 4, 6} k = 3 Output : [1, 2], [1, 4], [1, 6] E
    7 min read
  • Minimum change in given value so that it lies in all given Ranges
    Given an array of ranges arr[] of length N and a number D, the task is to find the minimum amount by which the number D should be changed such that D lies in every range of given array. Here a range consists of two integer [start, end] and D is said to be inside of range, if start ? D ? end. Example
    7 min read
  • Sort an array according to absolute difference with given value using Functors
    Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., the element having a minimum difference comes first and so on. Note: If two or more elements are at equal distance arrange them in same sequence as in the given array. Exa
    6 min read
  • Minimum elements inserted in a sorted array to form an Arithmetic progression
    Given a sorted array arr[], the task is to find minimum elements needed to be inserted in the array such that array forms an Arithmetic Progression.Examples: Input: arr[] = {1, 6, 8, 10, 14, 16} Output: 10 Explanation: Minimum elements required to form A.P. is 10. Transformed array after insertion o
    8 min read
  • C++ Program for Minimum product pair an array of positive Integers
    Given an array of positive integers. We are required to write a program to print the minimum product of any two numbers of the given array.Examples: Input : 11 8 5 7 5 100 Output : 25 Explanation : The minimum product of any two numbers will be 5 * 5 = 25. Input : 198 76 544 123 154 675 Output : 744
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences