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
- class Solution {
- public:
- int findPair(int n, int x, vector<int> &arr) {
- // Step 1: Sort the array
- sort(arr.begin(), arr.end());
- // Step 2: Initialize two pointers
- int i = 0, j = 1;
- // Step 3: Use a while loop to find the pair with the given difference
- while (i < n && j < n) {
- // Calculate the difference between the current pair of elements
- int diff = abs(arr[j] - arr[i]);
- // Step 4: Check if the difference equals the target value x
- if (diff == x && i != j) {
- // If we find such a pair, return 1
- return 1;
- } else if (diff < x) {
- // If the difference is less than x, move the second pointer to the right
- j++;
- } else {
- // If the difference is greater than x, move the first pointer to the right
- i++;
- }
- // Step 5: Ensure i and j do not overlap incorrectly
- if (i == j) {
- j++;
- }
- }
- // Step 6: If no such pair is found, return -1
- return -1;
- }
- };