Leetcode 1486 Solution

This article provides solution to leetcode question 1486 (find-the-distance-value-between-two-arrays)

https://leetcode.com/problems/find-the-distance-value-between-two-arrays

Solution

class Solution:
    def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
        arr1.sort()
        arr2.sort()

        print(arr1)
        print(arr2)

        i, j = 0, 0

        ans = 0
        while i < len(arr1):
            while j < len(arr2) - 1 and arr2[j] <= arr1[i]:
                j += 1

            if j == 0:
                min_dist = abs(arr2[j] - arr1[i])
            elif j == len(arr2) - 1:
                if len(arr2) == 1:
                    min_dist = abs(arr1[i] - arr2[j])
                else:
                    min_dist = min(abs(arr1[i] - arr2[j - 1]), abs(arr2[j] - arr1[i]))
            else:
                min_dist = min(arr1[i] - arr2[j - 1], arr2[j] - arr1[i])

            if min_dist > d:
                ans += 1

            i += 1

        return ans