Skip to main content
Back to problems
#1385
Easy Algorithms

Find the distance value between two arrays

Array Two Pointers Binary Search Sorting
71.5% acceptance
Feb 25, 2026
1021
3159
Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn find_the_distance_value(arr1: Vec<i32>, mut arr2: Vec<i32>, d: i32) -> i32 {
    arr2.sort_unstable();
    arr1.iter().filter(|&&x| {
      // Binary search: find if any arr2[j] satisfies |x - arr2[j]| <= d
      let lo = arr2.partition_point(|&y| y < x - d);
      lo >= arr2.len() || arr2[lo] > x + d
    }).count() as i32
  }
}