You are given two integer arrays arr1 and arr2, and an integer d.
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.
Example 1:
Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output: 2
Example 2:
Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
Output: 2
Example 3:
Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
Output: 1
arr1 and arr2 each have lengths between 1 and 500.d are all integers between -10000 and 10000.arr1 and arr2 will always be non-empty.arr1, we check all elements in arr2 to see if the condition |arr1[i] - arr2[j]| <= d is violated.arr2 and using binary search to find if there’s any element within the range [arr1[i] - d, arr1[i] + d].We’ll start with the brute force approach for simplicity.
from bisect import bisect_left, bisect_right
def findTheDistanceValue(arr1, arr2, d):
arr2.sort() # Sort arr2 to apply binary search
distance_value = 0
for num in arr1:
# Find the position where the current number should fit in sorted arr2
left = bisect_left(arr2, num - d)
right = bisect_right(arr2, num + d)
# If no element in arr2 is within the range
if left == right:
distance_value += 1
return distance_value
# Example runs
print(findTheDistanceValue([4,5,8], [10,9,1,8], 2)) # Output: 2
print(findTheDistanceValue([1,4,2,3], [-4,-3,6,10,20,30], 3)) # Output: 2
print(findTheDistanceValue([2,1,100,3], [-5,-2,10,-3,7], 6)) # Output: 1
arr2 takes O(n log n), where n is the length of arr2.arr1, we perform a binary search which is O(log n).O(m log n), where m is the length of arr1 and n is the length of arr2.This approach ensures efficient computation even when the input sizes are at their upper limits.
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?