find a pair with a given difference
Pattern: Two pointers
Sort, then move two pointers forward together. A gap that is too small moves the right one, and a gap that is too big moves the left one.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
You are given an array of whole numbers and a number n that is zero or more. Return true if two values at different
positions differ by exactly n (one minus the other equals n), and false otherwise. For example,
[5, 20, 3, 2, 50, 80] with n = 78 is true (80 - 2). With n = 0, the answer is true only if some value repeats.
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name
findPair is this guide's own. The function may reorder the array.
Think first
- After sorting, the pointers both start at the left. Why not one at each end, as for sums?
- If
arr[j] - arr[i]is too small, which pointer should move to make it bigger? - What must you be careful about when
n = 0?
Hints
Brute force, and why it fails
Check every pair: O(n²). A hash set of values answers "is x + n present?" in O(n) on average, with care needed for
n = 0. Sorting with two pointers is O(n log n) and needs no extra memory.
The key insight
In a sorted array, moving j right can only widen the gap and moving i right can only narrow it. So each comparison
tells you which pointer to move, and neither ever moves back.
Dry run
| gap | 1 |
|---|
arr = [5, 20, 3, 2, 50, 80] and n = 78, sorted to [2, 3, 5, 20, 50, 80]. Start with i = 0 and j = 1. The gap is 3 - 2 = 1, too small.
The plan
sort arr
i = 0, j = 1
while j < length(arr):
gap = arr[j] - arr[i]
if i != j and gap == n: return true
else if gap < n: j = j + 1
else:
i = i + 1
if i == j: j = j + 1
return false
Complexity
- Time
O(n log n)- Space
O(1)
Sorting dominates. The two-pointer walk is O(n), since each step moves a pointer forward.
Edge cases
n = 0with a repeated value, as in[1, 2, 2]: true.n = 0with no repeats: false.- One element: false.
- Negative values, as in
[-5, 3]withn = 8: true.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public boolean findPair(int[] arr, int n) {
Arrays.sort(arr);
int i = 0;
int j = 1;
while (j < arr.length) {
long diff = (long) arr[j] - arr[i];
if (i != j && diff == n) {
return true;
} else if (diff < n) {
j++; // need a bigger gap
} else {
i++; // need a smaller gap
if (i == j) {
j++; // keep the two positions different
}
}
}
return false;
}
}C++
class Solution {
public:
bool findPair(vector<int>& arr, int n) {
sort(arr.begin(), arr.end());
size_t i = 0;
size_t j = 1;
while (j < arr.size()) {
long long diff = static_cast<long long>(arr[j]) - arr[i];
if (i != j && diff == n) {
return true;
} else if (diff < n) {
j++; // need a bigger gap
} else {
i++; // need a smaller gap
if (i == j) {
j++; // keep the two positions different
}
}
}
return false;
}
};Python
class Solution:
def findPair(self, arr, n):
arr.sort()
i, j = 0, 1
while j < len(arr):
diff = arr[j] - arr[i]
if i != j and diff == n:
return True
elif diff < n:
j += 1 # need a bigger gap
else:
i += 1 # need a smaller gap
if i == j:
j += 1 # keep the two positions different
return FalseCommon mistakes
- Starting the pointers at opposite ends, which works for sums but not for differences.
- Letting
iequalj, which reports a value paired with itself whenn = 0. - Computing the gap in 32 bits when values can be near the limits.