Leetcode 1385. Find the Distance Value Between Two Arrays
Given two integer arrays arr1
and arr2
, and an integer d
, you need to find the distance value between the two arrays. The distance value is defined as the number of elements arr1[i]
such that there is no element arr2[j]
for which |arr1[i] - arr2[j]| <= d
.
-10^4
to 10^4
.500
elements.arr1
, check if there is any element in arr2
such that the absolute difference |arr1[i] - arr2[j]|
is less than or equal to d
.arr1[i]
, increment the counter.arr1
.arr1
, we check all elements in arr2
. This would result in a time complexity of O(n * m)
, where n
and m
are the lengths of arr1
and arr2
respectively.Here is the optimized approach using sorting and binary search in C++:
#include <vector>
#include <algorithm>
#include <cmath>
#include <iostream>
int findTheDistanceValue(std::vector<int>& arr1, std::vector<int>& arr2, int d) {
std::sort(arr2.begin(), arr2.end());
int distanceValue = 0;
for (int num : arr1) {
// Binary search to find the position in arr2 where this element could be
auto lower_bound_pos = std::lower_bound(arr2.begin(), arr2.end(), num - d);
auto upper_bound_pos = std::upper_bound(arr2.begin(), arr2.end(), num + d);
// If there is no element in the valid range, increment the count
if (lower_bound_pos == upper_bound_pos) {
distanceValue++;
}
}
return distanceValue;
}
int main() {
std::vector<int> arr1 = {4, 5, 8};
std::vector<int> arr2 = {10, 9, 1, 8};
int d = 2;
std::cout << "Distance Value: " << findTheDistanceValue(arr1, arr2, d) << std::endl;
return 0;
}
arr2
to enable binary search.arr1
, we use std::lower_bound
and std::upper_bound
to find the range in arr2
where elements fall within [num - d, num + d]
.lower_bound
and upper_bound
are the same, it means there is no element in arr2
within the distance d
from the current element in arr1
. Hence, we increment the distanceValue
.This approach ensures that we perform the distance check efficiently by leveraging sorting and binary search, yielding a time complexity of (O(n \log m)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?