Skip to problem
←

Pair with a Given Difference

Easy 0 attempts

Given an integer array arr and a non-negative target difference n, return true if there are two distinct indices i and j such that |arr[i] - arr[j]| = n. Otherwise, return false.

The array is not necessarily sorted. The pair can occur in either order and does not need to be adjacent. Return only whether a pair exists, not the pair itself.

When n = 0, two equal values at different indices are required: [1, 1] qualifies, but [1] does not. In [5, 20, 3, 2, 50, 80], the values 2 and 80 give a difference of 78.

Function contract

Implement findPair(arr, n).

Output: Return true if two distinct indices have an absolute value difference of n; otherwise return false.

Example 1

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.

Hash Set

Keep a set of values at earlier indices. For the current value x, a matching earlier value must be either x - n or x + n; checking both handles either input order.

Check before inserting x. This guarantees different indices, including when n = 0: a value matches only if another occurrence was already seen. If the scan ends without a match, no pair exists.

javascript
function findPair(arr, n) {
  const set = new Set();
  for (const x of arr) {
    if (set.has(x + n) || set.has(x - n)) return true;
    set.add(x);
  }
  return false;
}

Time: O(L) expected | Space: O(L), where L is arr.length (the parameter n is the target difference).

Loading discussion…

Saved in this browser only. Private to you.

JavaScript