Find a pair with the given difference

23 Jun, 2022
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 = 78Output: Pair Found: (2, 80)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Input: arr[] = {90, 70, 20, 80, 50}, n = 45Output: No Such Pair
Method 1: The simplest method is to run two loops, the outer loop picks the first element (smaller element) and the inner loop looks for the element picked by outer loop plus n. Time complexity of this method is O(n2).
Method 2: We can use sorting and Binary Search to improve time complexity to O(nLogn). The first step is to sort the array in ascending order. Once the array is sorted, traverse the array from left to right, and for each element arr[i], binary search for arr[i] + n in arr[i+1..n-1]. If the element is found, return the pair. Both first and second steps take O(nLogn). So overall complexity is O(nLogn). Method 3: The second step of the Method -2 can be improved to O(n). The first step remains the same. The idea for the second step is to take two index variables i and j, and initialize them as 0 and 1 respectively. Now run a linear loop. If arr[j] – arr[i] is smaller than n, we need to look for greater arr[j], so increment j. If arr[j] – arr[i] is greater than n, we need to look for greater arr[i], so increment i. Thanks to Aashish Barnwal for suggesting this approach. The following code is only for the second step of the algorithm, it assumes that the array is already sorted.  
C++
C
Java
Python
C#
PHP
Javascript
// C++ program to find a pair with the given difference#include <bits/stdc++.h>using namespace std; // The function assumes that the array is sortedbool findPair(int arr[], int size, int n){    // Initialize positions of two elements    int i = 0;    int j = 1;     // Search for a pair    while (i < size && j < size)    {        if (i != j && (arr[j] - arr[i] == n || arr[i] - arr[j] == n) )        {            cout << "Pair Found: (" << arr[i] <<                        ", " << arr[j] << ")";            return true;        }        else if (arr[j]-arr[i] < n)            j++;        else            i++;    }     cout << "No such pair";    return false;} // Driver program to test above functionint main(){    int arr[] = {1, 8, 30, 40, 100};    int size = sizeof(arr)/sizeof(arr[0]);    int n = -60;    findPair(arr, size, n);    return 0;} // This is code is contributed by rathbhupendra
// C program to find a pair with the given difference#include <stdio.h> // The function assumes that the array is sortedint findPair(int arr[], int size, int n){    // Initialize positions of two elements    int i = 0;     int j = 1;     // Search for a pair    while (i<size && j<size)    {        if (i != j && (arr[j] - arr[i] == n || arr[i] - arr[j] == n))        {            printf("Pair Found: (%d, %d)", arr[i], arr[j]);            return 1;        }        else if (arr[j]-arr[i] < n)            j++;        else            i++;    }     printf("No such pair");    return 0;} // Driver program to test above functionint main(){    int arr[] = {1, 8, 30, 40, 100};    int size = sizeof(arr)/sizeof(arr[0]);    int n = -60;    findPair(arr, size, n);    return 0;}
// Java program to find a pair with the given differenceimport java.io.*; class PairDifference{    // The function assumes that the array is sorted    static boolean findPair(int arr[],int n)    {        int size = arr.length;         // Initialize positions of two elements        int i = 0, j = 1;         // Search for a pair        while (i < size && j < size)        {            if (i != j && (arr[j] - arr[i] == n || arr[i] - arr[j] == n))            {                System.out.print("Pair Found: "+                                 "( "+arr[i]+", "+ arr[j]+" )");                return true;            }            else if (arr[j] - arr[i] < n)                j++;            else                i++;        }         System.out.print("No such pair");        return false;    }     // Driver program to test above function    public static void main (String[] args)    {        int arr[] = {1, 8, 30, 40, 100};        int n = -60;        findPair(arr,n);    }}/*This code is contributed by Devesh Agrawal*/
# Python program to find a pair with the given difference # The function assumes that the array is sorteddef findPair(arr,n):     size = len(arr)     # Initialize positions of two elements    i,j = 0,1     # Search for a pair    while i < size and j < size:         if i != j and arr[j]-arr[i] == n:            print "Pair found (",arr[i],",",arr[j],")"            return True         elif arr[j] - arr[i] < n:            j+=1        else:            i+=1    print "No pair found"    return False # Driver function to test above functionarr = [1, 8, 30, 40, 100]n = 60findPair(arr, n) # This code is contributed by Devesh Agrawal
// C# program to find a pair with the given differenceusing System; class GFG {         // The function assumes that the array is sorted    static bool findPair(int []arr, int n)    {        int size = arr.Length;         // Initialize positions of two elements        int i = 0, j = 1;         // Search for a pair        while (i < size && j < size)        {            if (i != j && arr[j] - arr[i] == n)            {                Console.Write("Pair Found: "                + "( " + arr[i] + ", " + arr[j] +" )");                                 return true;            }            else if (arr[j] - arr[i] < n)                j++;            else                i++;        }         Console.Write("No such pair");                 return false;    }     // Driver program to test above function    public static void Main ()    {        int []arr = {1, 8, 30, 40, 100};        int n = 60;                 findPair(arr, n);    }} // This code is contributed by Sam007.
<?php// PHP program to find a pair with// the given difference // The function assumes that the// array is sortedfunction findPair(&$arr, $size, $n){    // Initialize positions of    // two elements    $i = 0;    $j = 1;     // Search for a pair    while ($i < $size && $j < $size)    {        if ($i != $j && $arr[$j] -                        $arr[$i] == $n)        {            echo "Pair Found: " . "(" .                  $arr[$i] . ", " . $arr[$j] . ")";            return true;        }        else if ($arr[$j] - $arr[$i] < $n)            $j++;        else            $i++;    }     echo "No such pair";    return false;} // Driver Code$arr = array(1, 8, 30, 40, 100);$size = sizeof($arr);$n = 60;findPair($arr, $size, $n); // This code is contributed// by ChitraNayal?>
<script>        // JavaScript program for the above approach        // The function assumes that the array is sorted       function findPair(arr, size, n) {           // Initialize positions of two elements           let i = 0;           let j = 1;            // Search for a pair           while (i < size && j < size) {               if (i != j && arr[j] - arr[i] == n) {                   document.write("Pair Found: (" + arr[i] + ", " +                   arr[j] + ")");                   return true;               }               else if (arr[j] - arr[i] < n)                   j++;               else                   i++;           }            document.write("No such pair");           return false;       }        // Driver program to test above function        let arr = [1, 8, 30, 40, 100];       let size = arr.length;       let n = 60;       findPair(arr, size, n);     // This code is contributed by Potta Lokesh     </script>
Pair Found: (100, 40)
Time Complexity: O(n*log(n)) [Sorting is still required as first step], Where n is number of element in given arrayAuxiliary Space: O(1)
The above code can be simplified and can be made more understandable by reducing bunch of If-Else checks . Thanks to Nakshatra Chhillar for suggesting this simplification. We will understand simplifications through following code:
C++
// C++ program to find a pair with the given difference#include <bits/stdc++.h>using namespace std;bool findPair(int arr[], int size, int n){    // Step-1 Sort the array    sort(arr, arr + size);     // Initialize positions of two elements    int l = 0;    int r = 1;     // take absolute value of difference    // this does not affect the pair as A-B=diff is same as    // B-A= -diff    n = abs(n);     // Search for a pair     // These roop running conditions are sufficient    while (l <= r and r < size) {        int diff = arr[r] - arr[l];        if (diff == n            and l != r) // we need distinct elements in pair                        // so l!=r        {            cout << "Pair Found: (" << arr[l] << ", "                 << arr[r] << ")";            return true;        }        else if (diff > n) // try to reduce the diff            l++;        else // Note if l==r then r will be advanced thus no             // pair will be missed            r++;    }    cout << "No such pair";    return false;} // Driver program to test above functionint main(){    int arr[] = { 1, 8, 30, 40, 100 };    int size = sizeof(arr) / sizeof(arr[0]);    int n = -60;    findPair(arr, size, n);    cout << endl;    n = 20;    findPair(arr, size, n);    return 0;} // This code is contributed by Nakshatra Chhillar
Pair Found: (40, 100)
No such pair
Time Complexity: O(n*log(n)) [Sorting is still required as first step], Where n is number of element in given arrayAuxiliary Space: O(1)
Method 4 :Hashing can also be used to solve this problem. Create an empty hash table HT. Traverse the array, use array elements as hash keys and enter them in HT. Traverse the array again look for value n + arr[i] in HT. 
C++
Java
Python3
Javascript
// C++ program to find a pair with the given difference#include <bits/stdc++.h>using namespace std; // The function assumes that the array is sortedbool findPair(int arr[], int size, int n){    unordered_map<int, int> mpp;    for (int i = 0; i < size; i++) {        mpp[arr[i]]++;         // Check if any element whose frequency        // is greater than 1 exist or not for n == 0        if (n == 0 && mpp[arr[i]] > 1)            return true;    }     // Check if difference is zero and    // we are unable to find any duplicate or    // element whose frequency is greater than 1    // then no such pair found.    if (n == 0)        return false;     for (int i = 0; i < size; i++) {        if (mpp.find(n + arr[i]) != mpp.end()) {            cout << "Pair Found: (" << arr[i] << ", "                 << n + arr[i] << ")";            return true;        }    }     cout << "No Pair found";    return false;} // Driver program to test above functionint main(){    int arr[] = { 1, 8, 30, 40, 100 };    int size = sizeof(arr) / sizeof(arr[0]);    int n = -60;    findPair(arr, size, n);    return 0;}
// Java program for the above approachimport java.io.*;import java.util.*; class GFG{   // The function assumes that the array is sorted  static boolean findPair(int[] arr, int size, int n)  {    HashMap<Integer,            Integer> mpp = new HashMap<Integer,                                      Integer>();      // Traverse the array    for(int i = 0; i < size; i++)    {                  // Update frequency        // of arr[i]        mpp.put(arr[i],               mpp.getOrDefault(arr[i], 0) + 1);               // Check if any element whose frequency        // is greater than 1 exist or not for n == 0        if (n == 0 && mpp.get(arr[i]) > 1)            return true;    }       // Check if difference is zero and    // we are unable to find any duplicate or    // element whose frequency is greater than 1    // then no such pair found.    if (n == 0)        return false;     for (int i = 0; i < size; i++) {      if (mpp.containsKey(n + arr[i])) {        System.out.print("Pair Found: (" + arr[i] + ", " +                      + (n + arr[i]) + ")");        return true;      }    }    System.out.print("No Pair found");    return false;  }  // Driver Codepublic static void main(String[] args){    int[] arr = { 1, 8, 30, 40, 100 };    int size = arr.length;    int n = -60;    findPair(arr, size, n);}} // This code is contributed by code_hunt.
# Python program to find a pair with the given difference # The function assumes that the array is sorteddef findPair(arr, size, n):     mpp = {}     for i in range(size):        if arr[i] in mpp.keys():             mpp[arr[i]] += 1             if(n == 0 and mpp[arr[i]] > 1):                return true;        else:             mpp[arr[i]] = 1         if(n == 0):      return false;     for i in range(size):         if n + arr[i] in mpp.keys():            print("Pair Found: (" + str(arr[i]) + ", " + str(n + arr[i]) + ")")            return True         print("No Pair found")    return False # Driver program to test above functionarr = [ 1, 8, 30, 40, 100 ]size = len(arr)n = -60findPair(arr, size, n) # This code is contributed by shinjanpatra
<script>// Javascript program for the above approach // The function assumes that the array is sortedfunction findPair(arr, size, n) {  let mpp = new Map();   // Traverse the array  for (let i = 0; i < size; i++) {     // Update frequency    // of arr[i]    if (mpp.has(arr[i]))      mpp.set(arr[i], mpp.get(arr[i]) + 1);    else      mpp.set(arr[i], 1)     // Check if any element whose frequency    // is greater than 1 exist or not for n == 0    if (n == 0 && mpp.get(arr[i]) > 1)      return true;  }   // Check if difference is zero and  // we are unable to find any duplicate or  // element whose frequency is greater than 1  // then no such pair found.  if (n == 0)    return false;   for (let i = 0; i < size; i++) {    if (mpp.has(n + arr[i])) {      document.write("Pair Found: (" + arr[i] + ", " +        + (n + arr[i]) + ")");      return true;    }  }  document.write("No Pair found");  return false;} // Driver Codelet arr = [1, 8, 30, 40, 100];let size = arr.length;let n = -60;findPair(arr, size, n); // This code is contributed by Saurabh Jaiswal</script>
Pair Found: (100, 40)
Time Complexity: O(n), Where n is number of element in given arrayAuxiliary Space: O(n) 
Find a pair with the given difference | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersFind a pair with the given difference | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qODOVGzk6Zc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. 
ukasp
rathbhupendra
lokeshpotta20
gourabn2000
prasanna1995
shinjanpatra
sanjoy_62
code_hunt
harendrakumar123
_saurabh_jaiswal
nakshatra160201
Amazon
Binary Search
Visa
Searching
Sorting
Amazon
Visa
Searching
Sorting
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.