Pair with the given difference
Given an array arr and a target value N, determine whether two elements at distinct indices in the array differ by exactly N.
Input Format
Implement findPair(arr, n). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
arr = [5,20,3,2,50,80]
n = 78 Output
true Example 2
Input
arr = [1,2,3]
n = 0 Output
false Example 3
Input
arr = [1,1]
n = 0 Output
true Constraints
- 1 <= arr.length <= 10^5
- 1 <= arr[i] <= 10^5
- 0 <= n <= 10^5; the difference uses distinct indices.
Test Cases (3)
Case 1
Args: [[5,20,3,2,50,80],78]
Expected: true
Case 2
Args: [[1,2,3],0]
Expected: false
Case 3
Args: [[1,1],0]
Expected: true
Topics
Hash Set
function findPair(arr, n) {
const set = new Set();
n = Math.abs(n);
for (const x of arr) {
if (set.has(x + n) || set.has(x - n)) return true;
set.add(x);
}
return false;
}Time: O(n) | Space: O(n)
Saved in this browser only. Private to you.