Find the Distance Value Between Two Arrays (LeetCode 1385): Solution and Explanation
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
- Sort
arr2and setcount = 0. - For each
ainarr1, binary search withlo = 0,hi = len(arr2): ifarr2[mid] < a - dmovelotomid + 1, otherwise movehitomid. - When the search stops,
lois the index of the first value>= a - d(or the length ofarr2if there is none). - If
lois past the end orarr2[lo] > a + d, the window is empty, so incrementcount. - Return
count.
Step-by-step example
arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
- Sort arr2 to [1, 8, 9, 10].
- a = 4, window [2, 6]. The first value >= 2 is 8 at index 1. 8 > 6, so the window is empty and count = 1.
- a = 5, window [3, 7]. The first value >= 3 is again 8, which is past 7, so count = 2.
- a = 8, window [6, 10]. The first value >= 6 is 8, which is inside the window, so 8 is not counted.
- 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 count1class Solution {
2 public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
3 Arrays.sort(arr2);
4 int count = 0;
5 for (int a : arr1) {
6 int lo = 0, hi = arr2.length;
7 while (lo < hi) {
8 int mid = (lo + hi) / 2;
9 if (arr2[mid] < a - d) {
10 lo = mid + 1;
11 } else {
12 hi = mid;
13 }
14 }
15 if (lo == arr2.length || arr2[lo] > a + d) {
16 count++;
17 }
18 }
19 return count;
20 }
21}1class Solution {
2public:
3 int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {
4 sort(arr2.begin(), arr2.end());
5 int count = 0;
6 for (int a : arr1) {
7 int lo = 0, hi = arr2.size();
8 while (lo < hi) {
9 int mid = (lo + hi) / 2;
10 if (arr2[mid] < a - d) {
11 lo = mid + 1;
12 } else {
13 hi = mid;
14 }
15 }
16 if (lo == (int)arr2.size() || arr2[lo] > a + d) {
17 count++;
18 }
19 }
20 return count;
21 }
22};Time and space complexity
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).
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.