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).
Algorithm:
Start iterating through each element of the array using an outer loop.
For each element, start iterating again through each of the elements of the array except the one picked in outer loop using an inner loop.
If the difference between the current element and any of the elements of it is equal to the given difference, print both elements.
Continue the process until all possible pairs of elements are compared.
Time Complexity: O(n*n) as two nested for loops are executing both from 1 to n where n is size of input array. Space Complexity: O(1) as no extra space has been taken.
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++ program to find a pair with the given difference
# Python program to find a pair with the given difference
# The function assumes that the array is sorted
deffindPair(arr,n):
size =len(arr)
# Initialize positions of two elements
i,j =0,1
# Search for a pair
whilei < size andj < size:
ifi !=j andarr[j]-arr[i] ==n:
print"Pair found (",arr[i],",",arr[j],")"
returnTrue
elifarr[j] -arr[i] < n:
j+=1
else:
i+=1
print"No pair found"
returnFalse
# Driver function to test above function
arr =[1, 8, 30, 40, 100]
n =60
findPair(arr, n)
# This code is contributed by Devesh Agrawal
C#
// C# program to find a pair with the given difference
usingSystem;
classGFG {
// The function assumes that the array is sorted
staticboolfindPair(int[]arr, intn)
{
intsize = arr.Length;
// Initialize positions of two elements
inti = 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] +" )");
returntrue;
}
elseif(arr[j] - arr[i] < n)
j++;
else
i++;
}
Console.Write("No such pair");
returnfalse;
}
// Driver program to test above function
publicstaticvoidMain ()
{
int[]arr = {1, 8, 30, 40, 100};
intn = 60;
findPair(arr, n);
}
}
// This code is contributed by Sam007.
Javascript
<script>
// JavaScript program for the above approach
// The function assumes that the array is sorted
functionfindPair(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] + ")");
returntrue;
}
elseif(arr[j] - arr[i] < n)
j++;
else
i++;
}
document.write("No such pair");
returnfalse;
}
// 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>
PHP
<?php
// PHP program to find a pair with
// the given difference
// The function assumes that the
// array is sorted
functionfindPair(&$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] . ")";
returntrue;
}
elseif($arr[$j] - $arr[$i] < $n)
$j++;
else
$i++;
}
echo"No such pair";
returnfalse;
}
// Driver Code
$arr= array(1, 8, 30, 40, 100);
$size= sizeof($arr);
$n= 60;
findPair($arr, $size, $n);
// This code is contributed
// by ChitraNayal
?>
Output
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 array Auxiliary 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>
usingnamespacestd;
boolfindPair(intarr[], intsize, intn)
{
// Step-1 Sort the array
sort(arr, arr + size);
// Initialize positions of two elements
intl = 0;
intr = 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 loop running conditions are sufficient
while(l <= r and r < size) {
intdiff = 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] << ")";
returntrue;
}
elseif(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";
returnfalse;
}
// Driver program to test above function
intmain()
{
intarr[] = { 1, 8, 30, 40, 100 };
intsize = sizeof(arr) / sizeof(arr[0]);
intn = -60;
findPair(arr, size, n);
cout << endl;
n = 20;
findPair(arr, size, n);
return0;
}
// This code is contributed by Nakshatra Chhillar
Java
// Java program to find a pair with the given difference
importjava.io.*;
importjava.util.Arrays;
classGFG {
staticbooleanfindPair(intarr[], intsize, intn)
{
// Step-1 Sort the array
Arrays.sort(arr);
// Initialize positions of two elements
intl = 0;
intr = 1;
// take absolute value of difference
// this does not affect the pair as A-B=diff is same as
// B-A= -diff
n = Math.abs(n);
// Search for a pair
// These loop running conditions are sufficient
while(l <= r && r < size) {
intdiff = arr[r] - arr[l];
if(diff == n
&& l != r) // we need distinct elements in pair
// so l!=r
{
System.out.print("Pair Found: ("+ arr[l] + ", "
+ arr[r] + ")");
returntrue;
}
elseif(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++;
}
System.out.print("No such pair");
returnfalse;
}
// Driver program to test above function
publicstaticvoidmain (String[] args)
{
intarr[] = { 1, 8, 30, 40, 100};
intsize = arr.length;
intn = -60;
findPair(arr, size, n);
System.out.println();
n = 20;
findPair(arr, size, n);
}
}
// This code is contributed by Pushpesh Raj
Python3
# Python program to find a pair with the given difference
deffindPair( arr, size, n):
# Step-1 Sort the array
arr.sort();
# Initialize positions of two elements
l =0;
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 loop running conditions are sufficient
while(l <=r andr < size) :
diff =arr[r] -arr[l];
if(diff ==n andl !=r):
# we need distinct elements in pair
# so l!=r
print("Pair Found: (", arr[l] , ", "
, arr[r] , ")");
returnTrue;
elif(diff > n):# try to reduce the diff
l +=1;
else:# Note if l==r then r will be advanced thus no
# pair will be missed
r+=1;
print("No such pair");
returnFalse;
# Driver program to test above function
arr =[ 1, 8, 30, 40, 100];
size =len(arr);
n =-60;
findPair(arr, size, n);
n =20;
findPair(arr, size, n);
# This code is contributed by agrawalpoojaa976.
C#
// C# code implementation
usingSystem;
usingSystem.Collections;
publicclassGFG
{
staticboolfindPair(int[] arr, intsize, intn)
{
// Step-1 Sort the array
Array.Sort(arr);
// Initialize positions of two elements
intl = 0;
intr = 1;
// take absolute value of difference
// this does not affect the pair as A-B=diff is same
// as B-A= -diff
n = Math.Abs(n);
// Search for a pair
// These loop running conditions are sufficient
while(l <= r && r < size) {
intdiff = arr[r] - arr[l];
if(diff == n
&& l != r) // we need distinct elements in
// pair so l!=r
{
Console.Write("Pair Found: ("+ arr[l]
+ ", "+ arr[r] + ")");
returntrue;
}
elseif(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++;
}
Console.Write("No such pair");
returnfalse;
}
staticpublicvoidMain()
{
// Code
int[] arr = { 1, 8, 30, 40, 100 };
intsize = arr.Length;
intn = -60;
findPair(arr, size, n);
Console.WriteLine();
n = 20;
findPair(arr, size, n);
}
}
// This code is contributed by lokesh.
Javascript
// JavaScript program to find a pair with the given difference
const findPair = (arr, size, n) => {
// Step-1 Sort the array
arr.sort((a, b) => a - b);
// Initialize positions of two elements
let l = 0;
let r = 1;
// take absolute value of difference
// this does not affect the pair as A-B=diff is same as
// B-A= -diff
n = Math.abs(n);
// Search for a pair
// These loop running conditions are sufficient
while(l <= r && r < size) {
let diff = arr[r] - arr[l];
if(diff === n
&& l !== r) // we need distinct elements in pair
// so l!==r
{
console.log("Pair Found: ("+ arr[l] + ", "
+ arr[r] + ")");
returntrue;
}
elseif(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++;
}
console.log("No such pair");
returnfalse;
}
// Driver program to test above function
const main = () => {
let arr = [1, 8, 30, 40, 100];
let size = arr.length;
let n = -60;
findPair(arr, size, n);
console.log();
n = 20;
findPair(arr, size, n);
}
main();
Output
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 array Auxiliary 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++
// C++ program to find a pair with the given difference
#include <bits/stdc++.h>
usingnamespacestd;
// The function assumes that the array is sorted
boolfindPair(intarr[], intsize, intn)
{
unordered_map<int, int> mpp;
for(inti = 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)
returntrue;
}
// 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)
returnfalse;
for(inti = 0; i < size; i++) {
if(mpp.find(n + arr[i]) != mpp.end()) {
cout << "Pair Found: ("<< arr[i] << ", "
<< n + arr[i] << ")";
returntrue;
}
}
cout << "No Pair found";
returnfalse;
}
// Driver program to test above function
intmain()
{
intarr[] = { 1, 8, 30, 40, 100 };
intsize = sizeof(arr) / sizeof(arr[0]);
intn = -60;
findPair(arr, size, n);
return0;
}
Java
// Java program for the above approach
importjava.io.*;
importjava.util.*;
classGFG
{
// The function assumes that the array is sorted
staticbooleanfindPair(int[] arr, intsize, intn)
{
HashMap<Integer,
Integer> mpp = newHashMap<Integer,
Integer>();
// Traverse the array
for(inti = 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)
returntrue;
}
// 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)
returnfalse;
for(inti = 0; i < size; i++) {
if(mpp.containsKey(n + arr[i])) {
System.out.print("Pair Found: ("+ arr[i] + ", "+
+ (n + arr[i]) + ")");
returntrue;
}
}
System.out.print("No Pair found");
returnfalse;
}
// Driver Code
publicstaticvoidmain(String[] args)
{
int[] arr = { 1, 8, 30, 40, 100};
intsize = arr.length;
intn = -60;
findPair(arr, size, n);
}
}
// This code is contributed by code_hunt.
Python3
# Python program to find a pair with the given difference
Time Complexity: O(n), Where n is number of element in given array Auxiliary Space: O(n)
Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!