VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-a-pair-with-the-given-difference/

⇱ Pair with the given difference - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Pair with the given difference

Last Updated : 4 Apr, 2026

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: true
Explanation: The pair is {2, 80}.

Input: arr[] = [90, 70, 20, 80, 50], x = 45
Output: false
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.


Output
Yes

[Better Approach] Using Sorting and 2 Pointers - 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.

Output
Yes

[Expected Approach] 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

Output
Yes
Comment