Open In App

Pair with the given difference

Last Updated : 28 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an unsorted array and an integer x, the task is to find if there exists a pair of elements in the array whose absolute difference is x

Examples: 

Input: arr[] = [5, 20, 3, 2, 50, 80], x = 78
Output: Yes
Explanation: The pair is {2, 80}.

Input: arr[] = [90, 70, 20, 80, 50], x = 45
Output: No
Explanation: No such pair exists.

[Naive Approach] Using 2 Nested Loops - O(n^2) time and O(1) space

The idea is to use two nested loops to compare every possible pair of elements in the array, checking their absolute difference against the target value.

C++
// C++ program to find a pair with the given difference
#include <bits/stdc++.h>
using namespace std;

bool findPair(vector<int> &arr, int x) {
    int n = arr.size();
    
    // Compare each element with every other element
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            
            // Check if absolute difference matches target
            if (abs(arr[i] - arr[j]) == x) {
                return true;
            }
        }
    }
    
    return false;
}

int main() {
    vector<int> arr = {5, 20, 3, 2, 50, 80};
    int x = 78;
    if (findPair(arr, x)) {
        cout << "Yes";
    } else {
        cout << "No";
    }
    return 0;
}
Java
// Java program to find a pair with the given difference
import java.util.*;

class GfG {
    static boolean findPair(int[] arr, int x) {
        int n = arr.length;
        
        // Compare each element with every other element
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                
                // Check if absolute difference matches target
                if (Math.abs(arr[i] - arr[j]) == x) {
                    return true;
                }
            }
        }
        
        return false;
    }

    public static void main(String[] args) {
        int[] arr = {5, 20, 3, 2, 50, 80};
        int x = 78;
        if (findPair(arr, x)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
Python
# Python program to find a pair with the given difference

def findPair(arr, x):
    n = len(arr)
    
    # Compare each element with every other element
    for i in range(n):
        for j in range(i + 1, n):
            
            # Check if absolute difference matches target
            if abs(arr[i] - arr[j]) == x:
                return True
    
    return False

if __name__ == "__main__":
    arr = [5, 20, 3, 2, 50, 80]
    x = 78
    if findPair(arr, x):
        print("Yes")
    else:
        print("No")
C#
// C# program to find a pair with the given difference
using System;

class GfG {

    
    static bool findPair(int[] arr, int x) {
        int n = arr.Length;
        
        // Compare each element with every other element
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                
                // Check if absolute difference matches target
                if (Math.Abs(arr[i] - arr[j]) == x) {
                    return true;
                }
            }
        }
        
        return false;
    }

    static void Main() {
        int[] arr = {5, 20, 3, 2, 50, 80};
        int x = 78;
        if (findPair(arr, x)) {
            Console.WriteLine("Yes");
        } else {
            Console.WriteLine("No");
        }
    }
}
JavaScript
// JavaScript program to find a pair with the given difference

function findPair(arr, x) {
    let n = arr.length;
    
    // Compare each element with every other element
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            
            // Check if absolute difference matches target
            if (Math.abs(arr[i] - arr[j]) === x) {
                return true;
            }
        }
    }
    
    return false;
}

let arr = [5, 20, 3, 2, 50, 80];
let x = 78;
if (findPair(arr, x)) {
    console.log("Yes");
} else {
    console.log("No");
}

Output
Yes

[Expected Approach - 1] Using Sorting and Binary Search - O(n Log n) time and O(1) space

The idea is to first sort the array and then for each element, use binary search to efficiently find if its potential pair (with the target difference) exists in the remaining part of the array.

Step by step approach:

  1. Sort the input array in ascending order.
  2. Iterate through each element of sorted array.
  3. Compute the potential target value (current + difference).
  4. Use binary search to find this target in appropriate array segment. Return true if any potential pair is found.
  5. Return false if no pair exists after complete iteration.
C++
// C++ program to find a pair with the given difference
#include <bits/stdc++.h>
using namespace std;

// Function to find a pair with the given difference
bool findPair(vector<int> &arr, int x) {
    
    // Sort the array first
    sort(arr.begin(), arr.end());
    
    int n = arr.size();
    
    // For each element, search for its complement
    for (int i = 0; i < n; i++) {
        
        // Try finding arr[i] + x
        int target = arr[i] + x;
        
        // Binary search for target1
        if (binary_search(arr.begin() + i + 1, arr.end(), target)) {
            return true;
        }
    }
    
    return false;
}

int main() {
    vector<int> arr = {5, 20, 3, 2, 50, 80};
    int x = 78;
    if (findPair(arr, x)) {
        cout << "Yes";
    } else {
        cout << "No";
    }
    return 0;
}
Java
// Java program to find a pair with the given difference
import java.util.Arrays;

class GfG {

    // Function to find a pair with the given difference
    static boolean findPair(int[] arr, int x) {
        
        // Sort the array first
        Arrays.sort(arr);
        
        int n = arr.length;
        
        // For each element, search for its complement
        for (int i = 0; i < n; i++) {
            
            // Try finding arr[i] + x
            int target = arr[i] + x;
            
            // Binary search for target
            if (binarySearch(arr, i + 1, n - 1, target)) {
                return true;
            }
        }
        
        return false;
    }

    // Binary search function
    static boolean binarySearch(int[] arr, int left, int right, int key) {
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == key) {
                return true;
            } else if (arr[mid] < key) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] arr = {5, 20, 3, 2, 50, 80};
        int x = 78;
        if (findPair(arr, x)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
Python
# Python program to find a pair with the given difference

# Function to find a pair with the given difference
def findPair(arr, x):
    
    # Sort the array first
    arr.sort()
    
    n = len(arr)
    
    # For each element, search for its complement
    for i in range(n):
        
        # Try finding arr[i] + x
        target = arr[i] + x
        
        # Binary search for target
        if binarySearch(arr, i + 1, n - 1, target):
            return True
    
    return False

# Binary search function
def binarySearch(arr, left, right, key):
    while left <= right:
        mid = left + (right - left) // 2
        if arr[mid] == key:
            return True
        elif arr[mid] < key:
            left = mid + 1
        else:
            right = mid - 1
    return False

if __name__ == "__main__":
    arr = [5, 20, 3, 2, 50, 80]
    x = 78
    if findPair(arr, x):
        print("Yes")
    else:
        print("No")
C#
// C# program to find a pair with the given difference
using System;

class GfG {

    // Function to find a pair with the given difference
    static bool findPair(int[] arr, int x) {
        
        // Sort the array first
        Array.Sort(arr);
        
        int n = arr.Length;
        
        // For each element, search for its complement
        for (int i = 0; i < n; i++) {
            
            // Try finding arr[i] + x
            int target = arr[i] + x;
            
            // Binary search for target
            if (binarySearch(arr, i + 1, n - 1, target)) {
                return true;
            }
        }
        
        return false;
    }

    // Binary search function
    static bool binarySearch(int[] arr, int left, int right, int key) {
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == key) {
                return true;
            } else if (arr[mid] < key) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return false;
    }

    static void Main() {
        int[] arr = {5, 20, 3, 2, 50, 80};
        int x = 78;
        if (findPair(arr, x)) {
            Console.WriteLine("Yes");
        } else {
            Console.WriteLine("No");
        }
    }
}
JavaScript
// JavaScript program to find a pair with the given difference

// Function to find a pair with the given difference
function findPair(arr, x) {
    
    // Sort the array first
    arr.sort((a, b) => a - b);
    
    let n = arr.length;
    
    // For each element, search for its complement
    for (let i = 0; i < n; i++) {
        
        // Try finding arr[i] + x
        let target = arr[i] + x;
        
        // Binary search for target
        if (binarySearch(arr, i + 1, n - 1, target)) {
            return true;
        }
    }
    
    return false;
}

// Binary search function
function binarySearch(arr, left, right, key) {
    while (left <= right) {
        let mid = left + Math.floor((right - left) / 2);
        if (arr[mid] === key) {
            return true;
        } else if (arr[mid] < key) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return false;
}

let arr = [5, 20, 3, 2, 50, 80];
let x = 78;
if (findPair(arr, x)) {
    console.log("Yes");
} else {
    console.log("No");
}

Output
Yes

[Expected Approach - 2] Using Sorting and 2 Pointers Method - O(n Log n) time and O(1) space

The idea is to first sort the array in ascending order and then use two pointers to efficiently traverse the array, incrementing the second pointer (j) to find pairs with the exact target difference.

Step by step approach:

  1. Sort the array and initialize two variables: i (initially set to 0) and j (initially set to 1).
  2. While i is less than size of array:
    • While j is less than size of array and difference between arr[j] and arr[i] is less than x, increment j.
    • If j is less than size of array and i is not equal to j and difference is equal to x, then return true.
    • Increment i.
  3. If no pair is found, return false.
C++
// C++ program to find a pair with the given difference
#include <bits/stdc++.h>
using namespace std;

bool findPair(vector<int> &arr, int x) {
    int n = arr.size();
    
    // Sort the array.
    sort(arr.begin(), arr.end());
    
    int j = 1;
    
    for (int i=0; i<n; i++) {
        
        // Increment j till difference is 
        // less than x.
        while (j<n && arr[j]-arr[i] < x) j++;
        
        // If difference is x
        if (j<n && i != j && arr[j]-arr[i] == x) return true;
    }
    
    return false;
}

int main() {
    vector<int> arr = {5, 20, 3, 2, 50, 80};
    int x = 78;
    if (findPair(arr, x)) {
        cout << "Yes";
    } else {
        cout << "No";
    }
    return 0;
}
Java
// Java program to find a pair with the given difference
import java.util.Arrays;

class GfG {

    static boolean findPair(int[] arr, int x) {
        int n = arr.length;
        
        // Sort the array.
        Arrays.sort(arr);
        
        int j = 1;
        
        for (int i = 0; i < n; i++) {
            
            // Increment j till difference is 
            // less than x.
            while (j < n && arr[j] - arr[i] < x) j++;
            
            // If difference is x
            if (j < n && i != j && arr[j] - arr[i] == x) return true;
        }
        
        return false;
    }

    public static void main(String[] args) {
        int[] arr = {5, 20, 3, 2, 50, 80};
        int x = 78;
        if (findPair(arr, x)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
Python
# Python program to find a pair with the given difference

def findPair(arr, x):
    n = len(arr)
    
    # Sort the array.
    arr.sort()
    
    j = 1
    
    for i in range(n):
        
        # Increment j till difference is 
        # less than x.
        while j < n and arr[j] - arr[i] < x:
            j += 1
        
        # If difference is x
        if j < n and i != j and arr[j] - arr[i] == x:
            return True
    
    return False

if __name__ == "__main__":
    arr = [5, 20, 3, 2, 50, 80]
    x = 78
    if findPair(arr, x):
        print("Yes")
    else:
        print("No")
C#
// C# program to find a pair with the given difference
using System;

class GfG {

    static bool findPair(int[] arr, int x) {
        int n = arr.Length;
        
        // Sort the array.
        Array.Sort(arr);
        
        int j = 1;
        
        for (int i = 0; i < n; i++) {
            
            // Increment j till difference is 
            // less than x.
            while (j < n && arr[j] - arr[i] < x) j++;
            
            // If difference is x
            if (j < n && i != j && arr[j] - arr[i] == x) return true;
        }
        
        return false;
    }

    static void Main() {
        int[] arr = {5, 20, 3, 2, 50, 80};
        int x = 78;
        if (findPair(arr, x)) {
            Console.WriteLine("Yes");
        } else {
            Console.WriteLine("No");
        }
    }
}
JavaScript
// JavaScript program to find a pair with the given difference

function findPair(arr, x) {
    let n = arr.length;
    
    // Sort the array.
    arr.sort((a, b) => a - b);
    
    let j = 1;
    
    for (let i = 0; i < n; i++) {
        
        // Increment j till difference is 
        // less than x.
        while (j < n && arr[j] - arr[i] < x) j++;
        
        // If difference is x
        if (j < n && i !== j && arr[j] - arr[i] === x) return true;
    }
    
    return false;
}

let arr = [5, 20, 3, 2, 50, 80];
let x = 78;
if (findPair(arr, x)) {
    console.log("Yes");
} else {
    console.log("No");
}

Output
Yes

[Expected Approach - 3] Using Hash Set - O(n) time and O(n) space

The idea is to use a hash set to track each number and simultaneously checking if its potential complement (current number +/- difference) exists in the set.

Step by step approach:

  1. Create an empty hash set to store encountered numbers.
  2. Iterate through the array once:
    • For each number, check if its complement exists in set. If complement found, return true immediately.
    • If no complement found, add current number to set.
  3. Return false if no pair discovered after complete iteration
C++
// C++ program to find a pair with the given difference
#include <bits/stdc++.h>
using namespace std;

bool findPair(vector<int> &arr, int x) {
    unordered_set<int> st;
    
    for (int num : arr) {
        
        // Check if complement exists
        if (st.count(num + x) || st.count(num - x)) {
            return true;
        }
        
        st.insert(num);
    }
    
    return false;
}

int main() {
    vector<int> arr = {5, 20, 3, 2, 50, 80};
    int x = 78;
    if (findPair(arr, x)) {
        cout << "Yes";
    } else {
        cout << "No";
    }
    return 0;
}
Java
// Java program to find a pair with the given difference
import java.util.HashSet;

class GfG {

    static boolean findPair(int[] arr, int x) {
        
        HashSet<Integer> st = new HashSet<>();
        
        for (int num : arr) {
            
            // Check if complement exists
            if (st.contains(num + x) || st.contains(num - x)) {
                return true;
            }
            
            st.add(num);
        }
        
        return false;
    }

    public static void main(String[] args) {
        int[] arr = {5, 20, 3, 2, 50, 80};
        int x = 78;
        if (findPair(arr, x)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
Python
# Python program to find a pair with the given difference

def findPair(arr, x):
    
    st = set()
    
    for num in arr:
        
        # Check if complement exists
        if (num + x) in st or (num - x) in st:
            return True
        
        st.add(num)
    
    return False

if __name__ == "__main__":
    arr = [5, 20, 3, 2, 50, 80]
    x = 78
    if findPair(arr, x):
        print("Yes")
    else:
        print("No")
C#
// C# program to find a pair with the given difference
using System;
using System.Collections.Generic;

class GfG {

    static bool findPair(int[] arr, int x) {
        
        HashSet<int> st = new HashSet<int>();
        
        foreach (int num in arr) {
            
            // Check if complement exists
            if (st.Contains(num + x) || st.Contains(num - x)) {
                return true;
            }
            
            st.Add(num);
        }
        
        return false;
    }

    static void Main() {
        int[] arr = {5, 20, 3, 2, 50, 80};
        int x = 78;
        if (findPair(arr, x)) {
            Console.WriteLine("Yes");
        } else {
            Console.WriteLine("No");
        }
    }
}
JavaScript
// JavaScript program to find a pair with the given difference

function findPair(arr, x) {
    
    let st = new Set();
    
    for (let num of arr) {
        
        // Check if complement exists
        if (st.has(num + x) || st.has(num - x)) {
            return true;
        }
        
        st.add(num);
    }
    
    return false;
}

let arr = [5, 20, 3, 2, 50, 80];
let x = 78;
if (findPair(arr, x)) {
    console.log("Yes");
} else {
    console.log("No");
}

Output
Yes

Next Article

Similar Reads