Find the Distance Value Between Two Arrays

easy two pointers sorting binary search

Problem

You are given two integer arrays arr1 and arr2 and an integer d. The distance value is the number of elements arr1[i] for which there is no element arr2[j] satisfying |arr1[i] − arr2[j]| ≤ d. Return that count.

Inputarr1 = [4, 5, 8], arr2 = [10, 9, 1, 8], d = 2
Output2
For 4, the nearest arr2 value is 1 (distance 3) — safe. For 5, the nearest is 8 (distance 3) — safe. For 8, arr2 contains 8 (distance 0) and 9 (distance 1), both ≤ 2 — not counted. So 2 elements qualify.

def find_the_distance_value(arr1, arr2, d):
    arr2.sort()
    count = 0
    for x in arr1:
        lo, hi = 0, len(arr2)
        while lo < hi:
            mid = (lo + hi) // 2
            if arr2[mid] < x - d:
                lo = mid + 1
            else:
                hi = mid
        if lo == len(arr2) or arr2[lo] > x + d:
            count += 1
    return count
function findTheDistanceValue(arr1, arr2, d) {
  arr2.sort((a, b) => a - b);
  let count = 0;
  for (const x of arr1) {
    let lo = 0, hi = arr2.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (arr2[mid] < x - d) lo = mid + 1;
      else hi = mid;
    }
    if (lo === arr2.length || arr2[lo] > x + d) count++;
  }
  return count;
}
class Solution {
    public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
        Arrays.sort(arr2);
        int count = 0;
        for (int x : arr1) {
            int lo = 0, hi = arr2.length;
            while (lo < hi) {
                int mid = (lo + hi) >>> 1;
                if (arr2[mid] < x - d) lo = mid + 1;
                else hi = mid;
            }
            if (lo == arr2.length || arr2[lo] > x + d) count++;
        }
        return count;
    }
}
int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {
    sort(arr2.begin(), arr2.end());
    int count = 0;
    for (int x : arr1) {
        int lo = 0, hi = (int)arr2.size();
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (arr2[mid] < x - d) lo = mid + 1;
            else hi = mid;
        }
        if (lo == (int)arr2.size() || arr2[lo] > x + d) count++;
    }
    return count;
}
Time: O((n + m) log m) Space: O(1)