Find the Distance Value Between Two Arrays

For each element of arr1, binary search arr2 for the nearest neighbor and check the gap.

Easy
Time O((n + m) log m) Space O(1)
LeetCode
4 min read
binary-search sorting

Problem#

Given two arrays and integer d, return the count of elements in arr1 for which no element in arr2 lies within distance d.

Examples#

  • arr1 = [4,5,8], arr2 = [10,9,1,8], d = 22
  • arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 32
  • arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 61

Constraints#

  • 1 <= arr1.length, arr2.length <= 500, -1000 <= arr1[i], arr2[i] <= 1000, 0 <= d <= 100.

Approach#

Sort arr2. For each x in arr1, the only candidates that could be within d are the largest element <= x and the smallest element > x. Use lower_bound to locate both and check.

Solution#

Find the Distance Value Between Two Arrays
class Solution {
public:
int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {
sort(arr2.begin(), arr2.end());
int ans = 0;
for (int x : arr1) {
auto it = lower_bound(arr2.begin(), arr2.end(), x);
bool ok = true;
if (it != arr2.end() && abs(*it - x) <= d) ok = false;
if (it != arr2.begin() && abs(*prev(it) - x) <= d) ok = false;
if (ok) ++ans;
}
return ans;
}
};

Editorial#

Distance is minimized at the immediate neighbors in sorted order, so we only need two probes per element. Bounds-checking against begin() and end() avoids undefined behavior at the edges.

Complexity#

  • Time: O((n + m) log m).
  • Space: O(1) extra.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.