# C++ Program to Find a pair with the given difference

• Last Updated : 29 May, 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 = 78
Output: Pair Found: (2, 80)

Input: arr[] = {90, 70, 20, 80, 50}, n = 45
Output: No Such Pair```

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(n^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).
The second step of the above algorithm can be improved to O(n). The first step remain same. The idea for second step is take two index variables i and j, 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++ program to find a pair with the given difference ` `#include ` `using` `namespace` `std;`   `// The function assumes that the array is sorted ` `bool` `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) ` `        ``{ ` `            ``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 function ` `int` `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`

Output

`Pair Found: (40, 100)`

Efficient Approach:  Hashing can also be used to solve this problem. We first create an empty hash table HT. We then traverse in the array and use array elements as hash keys and enter them in HT. While traversing, if the given difference is 0 then we will check if any element is occurring more than one time or not. If n!=0, then we again Traverse the array and look for the value n + arr[i] in HT(hash table) as the difference between n+arr[i] and arr[i] is n.
Below is the code for the above approach.

## C++

 `// C++ program to find a pair with the given difference` `#include ` `using` `namespace` `std;`   `// The function assumes that the array is sorted` `bool` `findPair(``int` `arr[], ``int` `size, ``int` `n)` `{` `    ``// Using unordered_map for hashing` `    ``unordered_map<``int``, ``int``> mp;` `    ``for` `(``int` `i = 0; i < size; i++) {` `        ``// Using array elements as hash keys ` `        ``// and entering them in Hash table.` `        ``mp[arr[i]]++;`   `        ``// For n==0, checking if one element ` `        ``// is occurring more than 1 times` `        ``if` `(n==0 && mp[arr[i]] > 1)` `            ``return` `true``;` `    ``}`   `    ``// Check if the difference is ` `    ``// still 0 with no element` `    ``// occurring more than 1 times` `    ``if` `(n==0)` `        ``return` `false``;`   `    ``for` `(``int` `i = 0; i <= size-1; i++) ` `    ``{` `        ``// Checking if arr[i]+n is present or not` `        ``if` `(mp[arr[i]+n]) ` `        ``{` `            ``cout << ``"Pair Found: "``<< ``"("` `<< arr[i] << ``", "``<< n + arr[i] << ``")"``;` `            ``return` `true``;` `        ``}` `    ``}`   `    ``cout << ``"No such pair"``; ` `    ``return` `false``; ` `}`   `// Driver program to test above function` `int` `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 code is contributed by Pushpesh Raj.`

Output

`Pair Found: (40, 100)`

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

Please refer complete article on Find a pair with the given difference for more details!

My Personal Notes arrow_drop_up
Recommended Articles
Page :