Find Pair Given Difference- 17 May

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


Example 1:

Input:

n = 6

x = 78

arr[] = {5, 20, 3, 2, 5, 80}

Output:

1

Explanation:

Pair (2, 80) have absolute difference of 78.

Example 2:

Input:

n = 5

x = 45

arr[] = {90, 70, 20, 80, 50}

Output:

-1

Explanation:

There is no pair with absolute difference of 45.


HTML
  1. class Solution {
  2. public:
  3. int findPair(int n, int x, vector<int> &arr) {
  4. // Step 1: Sort the array
  5. sort(arr.begin(), arr.end());
  6. // Step 2: Initialize two pointers
  7. int i = 0, j = 1;
  8. // Step 3: Use a while loop to find the pair with the given difference
  9. while (i < n && j < n) {
  10. // Calculate the difference between the current pair of elements
  11. int diff = abs(arr[j] - arr[i]);
  12. // Step 4: Check if the difference equals the target value x
  13. if (diff == x && i != j) {
  14. // If we find such a pair, return 1
  15. return 1;
  16. } else if (diff < x) {
  17. // If the difference is less than x, move the second pointer to the right
  18. j++;
  19. } else {
  20. // If the difference is greater than x, move the first pointer to the right
  21. i++;
  22. }
  23. // Step 5: Ensure i and j do not overlap incorrectly
  24. if (i == j) {
  25. j++;
  26. }
  27. }
  28. // Step 6: If no such pair is found, return -1
  29. return -1;
  30. }
  31. };