{x}
blog image

Find the Distance Value Between Two Arrays

Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.

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
Explanation: 
For arr1[0]=4 we have: 
|4-10|=6 > d=2 
|4-9|=5 > d=2 
|4-1|=3 > d=2 
|4-8|=4 > d=2 
For arr1[1]=5 we have: 
|5-10|=5 > d=2 
|5-9|=4 > d=2 
|5-1|=4 > d=2 
|5-8|=3 > d=2
For arr1[2]=8 we have:
|8-10|=2 <= d=2
|8-9|=1 <= d=2
|8-1|=7 > d=2
|8-8|=0 <= d=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

 

Constraints:

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

Solution Explanation: Find the Distance Value Between Two Arrays

This problem asks us to find the number of elements in arr1 that have a distance greater than d from all elements in arr2. The distance between two numbers is their absolute difference.

The most efficient approach leverages sorting and binary search.

  1. Sort arr2: Sorting arr2 allows us to efficiently check for elements within the distance d of an element from arr1 using binary search.

  2. Iterate through arr1: For each element x in arr1, we perform a binary search on the sorted arr2 to find the smallest element greater than or equal to x - d.

  3. Binary Search: The bisect_left (or equivalent in other languages) function finds the insertion point for x - d in arr2. This index i represents the position where x - d would be inserted to maintain sorted order.

  4. Check Distance:

    • If i is equal to the length of arr2, it means all elements in arr2 are less than x - d, so the distance condition is satisfied.
    • Otherwise, we check if the element at index i (arr2[i]) is greater than x + d. If it is, then all elements in arr2 from index i onwards are greater than x + d, meaning the distance condition is met. If arr2[i] is less than or equal to x + d, the distance condition is not satisfied.
  5. Increment Count: If the distance condition is met, we increment a counter ans.

  6. Return Count: Finally, we return the ans, which represents the number of elements in arr1 that satisfy the distance condition.

Time Complexity Analysis

  • Sorting arr2 takes O(n log n) time, where n is the length of arr2.
  • Iterating through arr1 takes O(m) time, where m is the length of arr1.
  • For each element in arr1, the binary search takes O(log n) time.
  • Therefore, the overall time complexity is O(m log n + n log n), which simplifies to O((m+n) log n).

Space Complexity Analysis

The space complexity depends on the sorting algorithm used. In-place sorting algorithms have a space complexity of O(1), while merge sort has O(n) space complexity. Using Python's sorted() or similar functions that might use merge sort, the space complexity would be O(n). Using in-place sorting (like in C++'s ranges::sort) would be O(1) auxiliary space. Overall, we can say the space complexity is dominated by the sorting and is O(n) in the worst case (merge sort). The auxiliary space used in the rest of the algorithm is O(1)

Code Examples (with explanations)

Python

import bisect
 
class Solution:
    def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
        arr2.sort()  # Sort arr2 for efficient binary search
        ans = 0
        for x in arr1:
            i = bisect_left(arr2, x - d) #Find insertion point of x-d in arr2
            if i == len(arr2) or arr2[i] > x + d: #Check if distance condition is met
                ans += 1
        return ans
 

Java

import java.util.Arrays;
 
class Solution {
    public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
        Arrays.sort(arr2); // Sort arr2
        int ans = 0;
        for (int x : arr1) {
            int i = Arrays.binarySearch(arr2, x - d); //Binary search for x - d
            i = i < 0 ? -i - 1 : i; //Handle case where x-d is not found
            if (i == arr2.length || arr2[i] > x + d) { //Check distance condition
                ans++;
            }
        }
        return ans;
    }
}

C++ (using ranges library)

#include <algorithm>
#include <vector>
#include <ranges>
 
class Solution {
public:
    int findTheDistanceValue(std::vector<int>& arr1, std::vector<int>& arr2, int d) {
        std::ranges::sort(arr2); //Sort arr2
        int ans = 0;
        for (int x : arr1) {
            auto it = std::ranges::lower_bound(arr2, x - d); //lower_bound for binary search
            if (it == arr2.end() || *it > x + d) { //Check distance condition
                ans++;
            }
        }
        return ans;
    }
};

These code examples demonstrate the core logic using different languages. Remember to handle the case where x - d is not found in arr2 appropriately (as shown in the Java example). The choice of language affects the specifics of sorting and binary search implementation but the core algorithm remains the same.