Find the Distance Value Between Two Arrays — LeetCode 1385 Python Solution

EasyArrayTwo PointersBinary SearchSorting
Problem
#1385
Reading time
2 min

The problem

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

Input
arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output
2
Explanation
For arr1[0]=4 we have:

Python solution

Python
class Solution:
    def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
        arr2.sort()
        ans = 0
        for x in arr1:
            i = bisect_left(arr2, x - d)
            ans += i == len(arr2) or arr2[i] > x + d
        return ans

Complexity

MeasureComplexity
TimeO((m + n) \times \log n)
SpaceO(\log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1385. Find the Distance Value Between Two Arrays is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1385. Find the Distance Value Between Two Arrays?
LeetCode 1385. Find the Distance Value Between Two Arrays is rated Easy on LeetCode.
What is the time complexity of LeetCode 1385. Find the Distance Value Between Two Arrays?
The Python solution on this page runs in O((m + n) \times \log n).
What is the space complexity of LeetCode 1385. Find the Distance Value Between Two Arrays?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 1385. Find the Distance Value Between Two Arrays cover?
LeetCode 1385. Find the Distance Value Between Two Arrays is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview