Pair with the given difference - GeeksforGeeks

Pair with the given difference

Last Updated : 9 Oct, 2026

Given an array, arr[] and an integer x, return true if there exists a pair of elements in the array whose absolute difference is x, otherwise, return false.

Examples: 

Input: arr[] = [5, 20, 3, 2, 50, 80], x = 78
Output: true
Explanation: The pair (2, 80) has an absolute difference of 78.

Input: arr[] = [90, 70, 20, 80, 50], x = 45
Output: false
Explanation: No pair of elements has an absolute difference of 45.

Try It Yourself
redirect icon

[Naive Approach] Two Loops - O(n^2) Time and O(1) Space

The idea is to check every possible pair and compare its absolute difference with x.

  • Use two loops to consider each pair of elements.
  • If the absolute difference of a pair is x, return true.
  • If no such pair is found, return false.
C++
#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 << "true";
    } else {
        cout << "false";
    }
    return 0;
}
Java
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("true");
        } else {
            System.out.println("false");
        }
    }
}
Python
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("true")
    else:
        print("false")
C#
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("true");
        } else {
            Console.WriteLine("false");
        }
    }
}
JavaScript
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;
}

// Driver code
let arr = [5, 20, 3, 2, 50, 80];
let x = 78;
if (findPair(arr, x)) {
    console.log("true");
} else {
    console.log("false");
}

Output
Yes

[Better Approach] Sorting - O(n log n) Time and O(1) Space

The idea is to sort the array and use two pointers to find a pair with the required difference.

  • Sort the array in ascending order.
  • Initialize two pointers i = 0 and j = 1.
  • If arr[j] - arr[i] is less than x, increment j.
  • If it is greater than x, increment i.
  • If it is equal to x, return true.
  • Continue until either pointer reaches the end of the array.
  • Return false if no such pair is found.
C++
#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 << "true";
    } else {
        cout << "false";
    }
    return 0;
}
Java
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("true");
        } else {
            System.out.println("false");
        }
    }
}
Python
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("true")
    else:
        print("false")
C#
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("true");
        } else {
            Console.WriteLine("false");
        }
    }
}
JavaScript
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;
}

// Driver code
let arr = [5, 20, 3, 2, 50, 80];
let x = 78;
if (findPair(arr, x)) {
    console.log("true");
} else {
    console.log("false");
}

Output
true

[Expected Approach] Hash Set - O(n) Time and O(n) Space

The idea is to store the elements seen so far in a set and check for an element with difference x.

  • For each arr[i], check if arr[i] + x or arr[i] - x is present in the set.
  • If either value exists, return true.
  • Otherwise, add arr[i] to the set.
  • If no pair is found, return false.

Consider arr[] = [5, 20, 3, 2, 50, 80] and x = 78.

Start with an empty set.

  • For 5, neither 5 + 78 = 83 nor 5 - 78 = -73 is present. Add 5.
  • For 20, neither 98 nor -58 is present. Add 20.
  • For 3, neither 81 nor -75 is present. Add 3.
  • For 2, neither 80 nor -76 is present. Add 2.
  • For 50, neither 128 nor -28 is present. Add 50.
  • For 80, 80 - 78 = 2, and 2 is already in the set.

Thus, the pair (2, 80) has difference 78, so the result is true.

C++
#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 << "true";
    } else {
        cout << "false";
    }
    return 0;
}
Java
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("true");
        } else {
            System.out.println("false");
        }
    }
}
Python
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("true")
    else:
        print("false")
C#
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("true");
        } else {
            Console.WriteLine("false");
        }
    }
}
JavaScript
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;
}

// Driver code
let arr = [5, 20, 3, 2, 50, 80];
let x = 78;
if (findPair(arr, x)) {
    console.log("true");
} else {
    console.log("false");
}

Output
true
Comment