Find a pair with the given difference
Last Updated :
28 Dec, 2023
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
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.
- If no pair found, print “No such pair”.
Below is the implementation of the approach:
C++
#include<bits/stdc++.h>
using namespace std;
void findPair( int arr[], int n, int diff) {
for ( int i=0; i<n; i++) {
for ( int j=0; j<n; j++) {
if (i == j)
continue ;
if ((arr[j] - arr[i]) == diff) {
cout << "Pair Found: (" << arr[i] << ", " << arr[j] << ")" ;
return ;
}
}
}
cout << "No such pair" ;
}
int main() {
int arr[] = { 1, 8, 30, 40, 100 };
int n = sizeof (arr)/ sizeof (arr[0]);
int diff = -60;
findPair(arr, n, diff);
return 0;
}
|
Java
import java.util.Arrays;
public class FindPairWithDifference {
static void findPair( int [] arr, int n, int diff) {
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < n; j++) {
if (i == j)
continue ;
if ((arr[j] - arr[i]) == diff) {
System.out.println( "Pair Found: (" + arr[i] + ", " + arr[j] + ")" );
return ;
}
}
}
System.out.println( "No such pair" );
}
public static void main(String[] args) {
int [] arr = { 1 , 8 , 30 , 40 , 100 };
int n = arr.length;
int diff = - 60 ;
findPair(arr, n, diff);
}
}
|
Python3
def find_pair(arr, n, diff):
for i in range (n):
for j in range (n):
if i = = j:
continue
if arr[j] - arr[i] = = diff:
print (f "Pair Found: ({arr[i]}, {arr[j]})" )
return
print ( "No such pair" )
arr = [ 1 , 8 , 30 , 40 , 100 ]
n = len (arr)
diff = - 60
find_pair(arr, n, diff)
|
C#
using System;
class MainClass {
static void FindPair( int [] arr, int n, int diff) {
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
if (i == j)
continue ;
if ((arr[j] - arr[i]) == diff) {
Console.WriteLine($ "Pair Found: ({arr[i]}, {arr[j]})" );
return ;
}
}
}
Console.WriteLine( "No such pair" );
}
public static void Main ( string [] args) {
int [] arr = { 1, 8, 30, 40, 100 };
int n = arr.Length;
int diff = -60;
FindPair(arr, n, diff);
}
}
|
Javascript
function findPair(arr, diff) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (i === j) {
continue ;
}
if (arr[j] - arr[i] === diff) {
console.log(`Pair Found: (${arr[i]}, ${arr[j]})`);
return ;
}
}
}
console.log( 'No such pair' );
}
const arr = [1, 8, 30, 40, 100];
const diff = -60;
findPair(arr, diff);
|
Output
Pair Found: (100, 40)
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++
#include <bits/stdc++.h>
using namespace std;
bool findPair( int arr[], int size, int n)
{
int i = 0;
int j = 1;
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 ;
}
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;
}
|
C
#include <stdio.h>
int findPair( int arr[], int size, int n)
{
int i = 0;
int j = 1;
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;
}
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;
}
|
Java
import java.io.*;
class PairDifference
{
static boolean findPair( int arr[], int n)
{
int size = arr.length;
int i = 0 , j = 1 ;
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 ;
}
public static void main (String[] args)
{
int arr[] = { 1 , 8 , 30 , 40 , 100 };
int n = - 60 ;
findPair(arr,n);
}
}
|
Python
def findPair(arr,n):
size = len (arr)
i,j = 0 , 1
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
arr = [ 1 , 8 , 30 , 40 , 100 ]
n = 60
findPair(arr, n)
|
C#
using System;
class GFG {
static bool findPair( int []arr, int n)
{
int size = arr.Length;
int i = 0, j = 1;
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 ;
}
public static void Main ()
{
int []arr = {1, 8, 30, 40, 100};
int n = 60;
findPair(arr, n);
}
}
|
Javascript
<script>
function findPair(arr, size, n) {
let i = 0;
let j = 1;
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 ;
}
let arr = [1, 8, 30, 40, 100];
let size = arr.length;
let n = 60;
findPair(arr, size, n);
</script>
|
PHP
<?php
function findPair(& $arr , $size , $n )
{
$i = 0;
$j = 1;
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;
}
$arr = array (1, 8, 30, 40, 100);
$size = sizeof( $arr );
$n = 60;
findPair( $arr , $size , $n );
?>
|
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++
#include <bits/stdc++.h>
using namespace std;
bool findPair( int arr[], int size, int n)
{
sort(arr, arr + size);
int l = 0;
int r = 1;
n = abs (n);
while (l <= r and r < size) {
int diff = arr[r] - arr[l];
if (diff == n
and l != r)
{
cout << "Pair Found: (" << arr[l] << ", "
<< arr[r] << ")" ;
return true ;
}
else if (diff > n)
l++;
else
r++;
}
cout << "No such pair" ;
return false ;
}
int 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;
}
|
Java
import java.io.*;
import java.util.Arrays;
class GFG {
static boolean findPair( int arr[], int size, int n)
{
Arrays.sort(arr);
int l = 0 ;
int r = 1 ;
n = Math.abs(n);
while (l <= r && r < size) {
int diff = arr[r] - arr[l];
if (diff == n
&& l != r)
{
System.out.print( "Pair Found: (" + arr[l] + ", "
+ arr[r] + ")" );
return true ;
}
else if (diff > n)
l++;
else
r++;
}
System.out.print( "No such pair" );
return false ;
}
public static void main (String[] args)
{
int arr[] = { 1 , 8 , 30 , 40 , 100 };
int size = arr.length;
int n = - 60 ;
findPair(arr, size, n);
System.out.println();
n = 20 ;
findPair(arr, size, n);
}
}
|
Python3
def findPair( arr, size, n):
arr.sort();
l = 0 ;
r = 1 ;
n = abs (n);
while (l < = r and r < size) :
diff = arr[r] - arr[l];
if (diff = = n and l ! = r):
print ( "Pair Found: (" , arr[l] , ", "
, arr[r] , ")" );
return True ;
elif (diff > n):
l + = 1 ;
else :
r + = 1 ;
print ( "No such pair" );
return False ;
arr = [ 1 , 8 , 30 , 40 , 100 ];
size = len (arr);
n = - 60 ;
findPair(arr, size, n);
n = 20 ;
findPair(arr, size, n);
|
C#
using System;
using System.Collections;
public class GFG
{
static bool findPair( int [] arr, int size, int n)
{
Array.Sort(arr);
int l = 0;
int r = 1;
n = Math.Abs(n);
while (l <= r && r < size) {
int diff = arr[r] - arr[l];
if (diff == n
&& l != r)
{
Console.Write( "Pair Found: (" + arr[l]
+ ", " + arr[r] + ")" );
return true ;
}
else if (diff > n)
l++;
else
r++;
}
Console.Write( "No such pair" );
return false ;
}
static public void Main()
{
int [] arr = { 1, 8, 30, 40, 100 };
int size = arr.Length;
int n = -60;
findPair(arr, size, n);
Console.WriteLine();
n = 20;
findPair(arr, size, n);
}
}
|
Javascript
const findPair = (arr, size, n) => {
arr.sort((a, b) => a - b);
let l = 0;
let r = 1;
n = Math.abs(n);
while (l <= r && r < size) {
let diff = arr[r] - arr[l];
if (diff === n
&& l !== r)
{
console.log( "Pair Found: (" + arr[l] + ", "
+ arr[r] + ")" );
return true ;
}
else if (diff > n)
l++;
else
r++;
}
console.log( "No such pair" );
return false ;
}
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++
#include <bits/stdc++.h>
using namespace std;
bool findPair( int arr[], int size, int n)
{
unordered_map< int , int > mpp;
for ( int i = 0; i < size; i++) {
mpp[arr[i]]++;
if (n == 0 && mpp[arr[i]] > 1)
return true ;
}
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 ;
}
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;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static boolean findPair( int [] arr, int size, int n)
{
HashMap<Integer,
Integer> mpp = new HashMap<Integer,
Integer>();
for ( int i = 0 ; i < size; i++)
{
mpp.put(arr[i],
mpp.getOrDefault(arr[i], 0 ) + 1 );
if (n == 0 && mpp.get(arr[i]) > 1 )
return true ;
}
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 ;
}
public static void main(String[] args)
{
int [] arr = { 1 , 8 , 30 , 40 , 100 };
int size = arr.length;
int n = - 60 ;
findPair(arr, size, n);
}
}
|
Python3
def 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
arr = [ 1 , 8 , 30 , 40 , 100 ]
size = len (arr)
n = - 60
findPair(arr, size, n)
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static bool findPair( int [] arr, int size, int n)
{
Dictionary< int , int > mpp = new Dictionary< int , int >();
for ( int i = 0; i < size; i++)
{
mpp[arr[i]]=mpp.GetValueOrDefault(arr[i], 0) + 1;
if (n == 0 && mpp[arr[i]] > 1)
return true ;
}
if (n == 0)
return false ;
for ( int i = 0; i < size; i++) {
if (mpp.ContainsKey(n + arr[i])) {
Console.WriteLine( "Pair Found: (" + arr[i] + ", " +
+ (n + arr[i]) + ")" );
return true ;
}
}
Console.WriteLine( "No Pair found" );
return false ;
}
public static void Main( string []args)
{
int [] arr = { 1, 8, 30, 40, 100 };
int size = arr.Length;
int n = -60;
findPair(arr, size, n);
}
}
|
Javascript
<script>
function findPair(arr, size, n) {
let mpp = new Map();
for (let i = 0; i < size; i++) {
if (mpp.has(arr[i]))
mpp.set(arr[i], mpp.get(arr[i]) + 1);
else
mpp.set(arr[i], 1)
if (n == 0 && mpp.get(arr[i]) > 1)
return true ;
}
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 ;
}
let arr = [1, 8, 30, 40, 100];
let size = arr.length;
let n = -60;
findPair(arr, size, n);
</script>
|
Output
Pair Found: (100, 40)
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.
Please Login to comment...