Find the Distance Value Between Two Arrays

Too many down votes. Read the problem statement in the Solutions tab.

The task is to return the distance value between two arrays arr1 and arr2. The distance value is the count of elements in arr1 for which there is no element in arr2 such that the absolute difference between them is less than or equal to d.

Let’s follow a simple brute force approach where for each element in arr1, we check all elements in arr2 and increase our count if no such element is found in arr2 which satisfies the given condition.

Here is the Python code:

1
2
3
4
5
6
7
class Solution:
    def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
        count = 0
        for num1 in arr1:
            if all(abs(num1 - num2) > d for num2 in arr2):
                count += 1
        return count

In the above code:

  • We initialize a variable count to 0.
  • For each element (num1) in arr1, we check all elements (num2) in arr2 to see if the absolute difference between num1 and num2 is more than d.
  • If it is for all num2, we increment count because there is no element in arr2 satisfying the condition for that num1.
  • Finally, we return count which is our answer.

The time complexity of this solution is O(n*m), where n is the size of arr1 and m is the size of arr2.