#1385

Find the Distance Value Between Two Arrays

Easy
ArrayTwo PointersBinary SearchSortingBinary SearchSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n + m log m)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n + m log m)Space O(1)

By sorting arr2 and using binary search, we can efficiently find the closest elements to each element in arr1. This reduces the number of comparisons significantly.

⚙️

Algorithm

6 steps
  1. 1Step 1: Sort arr2.
  2. 2Step 2: Initialize a counter to zero for counting distance values.
  3. 3Step 3: For each element in arr1, use binary search to find the position of the closest element in arr2.
  4. 4Step 4: Check the closest elements to see if their absolute difference with the current arr1 element is within d.
  5. 5Step 5: If no such element is found, increment the counter.
  6. 6Step 6: Return the counter as the result.
solution.py12 lines
1# Full working Python code
2import bisect
3
4def findTheDistanceValue(arr1, arr2, d):
5    arr2.sort()
6    count = 0
7    for num1 in arr1:
8        pos = bisect.bisect_left(arr2, num1)
9        if (pos < len(arr2) and abs(arr2[pos] - num1) <= d) or (pos > 0 and abs(arr2[pos - 1] - num1) <= d):
10            continue
11        count += 1
12    return count

Complexity note: The sorting of arr2 takes O(m log m), and for each element in arr1, we perform a binary search which takes O(log m), leading to an overall complexity of O(n log n + m log m).

  • 1Sorting arr2 allows for efficient searching of closest elements.
  • 2Using binary search reduces the number of comparisons significantly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.