Find the Distance Value Between Two Arrays (LeetCode 1385): Solution and Explanation

Easy
Array
Two Pointers
Binary Search
Sorting

Given arrays arr1, arr2 and a distance d, count the values in arr1 that are more than d away from every value in arr2. With arr1 = [4,5,8], arr2 = [10,9,1,8] and d = 2 the answer is 2, because 4 and 5 are far from everything while 8 is not.

Intuition

For one value a, an element x of arr2 is too close when |a - x| <= d, which is the same as x lying in the window [a - d, a + d]. So the question for each a is simply whether that window contains any value of arr2.

Comparing a with every value of arr2 answers it, but on a sorted arr2 there is a much cheaper test. The values of arr2 that could land in the window form a contiguous block, and the leftmost candidate is the first value that is at least a - d.

If that first value exists and is at most a + d, it is inside the window and a is blocked. If it does not exist, or it already overshoots a + d, then everything smaller is below the window and everything larger is above it, so the window is empty and a counts.

Finding the first value >= a - d is a lower-bound binary search, so each element of arr1 costs O(log m).

Approach: Sort arr2 and binary search the window

  1. Sort arr2 and set count = 0.
  2. For each a in arr1, binary search with lo = 0, hi = len(arr2): if arr2[mid] < a - d move lo to mid + 1, otherwise move hi to mid.
  3. When the search stops, lo is the index of the first value >= a - d (or the length of arr2 if there is none).
  4. If lo is past the end or arr2[lo] > a + d, the window is empty, so increment count.
  5. Return count.

Step-by-step example

arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
  1. Sort arr2 to [1, 8, 9, 10].
  2. a = 4, window [2, 6]. The first value >= 2 is 8 at index 1. 8 > 6, so the window is empty and count = 1.
  3. a = 5, window [3, 7]. The first value >= 3 is again 8, which is past 7, so count = 2.
  4. a = 8, window [6, 10]. The first value >= 6 is 8, which is inside the window, so 8 is not counted.
  5. Return 2.

Code: Python, Java, C++

1class Solution:
2    def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
3        arr2.sort()
4        count = 0
5        for a in arr1:
6            lo, hi = 0, len(arr2)
7            while lo < hi:
8                mid = (lo + hi) // 2
9                if arr2[mid] < a - d:
10                    lo = mid + 1
11                else:
12                    hi = mid
13            if lo == len(arr2) or arr2[lo] > a + d:
14                count += 1
15        return count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O((n + m) log m)

Sorting arr2 costs O(m log m) and each of the n values of arr1 does one binary search of O(log m).

Space

O(1)

Only a few indices are kept, apart from whatever the language's sort uses internally.

Other approaches

Brute force over all pairs (time O(n * m), space O(1))

For every a, scan all of arr2 and stop at the first value within d. Simple and fine for 500 by 500 inputs.

Sort both arrays and sweep with two pointers (time O(n log n + m log m), space O(1))

Sort arr1 too and move one pointer in arr2 forward as a grows, since the lower edge a - d only increases. Each pointer moves at most its array's length.

Common mistakes

  • Checking only the value nearest to a from one side. The closest value can be just below a or just above it; searching for the first value >= a - d covers both sides at once.
  • Forgetting the case where every arr2 value is smaller than a - d, so the search index equals the array length and must not be read.
  • Using a strict comparison at the window edges. A difference of exactly d counts as too close.
  • Counting distinct values instead of positions. Duplicates in arr1 are each counted on their own.

Frequently asked questions

Why is checking one element of arr2 enough?

In sorted order, values below the first one that is >= a - d are all outside the window on the left. If that first value is also above a + d, every later value is even larger, so nothing lands in the window.

Does d = 0 need special handling?

No. The window shrinks to the single point a, and the search simply checks whether a itself appears in arr2.

Is the binary search worth it for such small inputs?

The brute force passes, but the binary search version shows the general technique: turn a distance condition into a window and query a sorted array for it.