Find the Distance Value Between Two Arrays - 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.

In other words, count how many elements in arr1 are more than distance d away from all elements in arr2.

Input & Output

Example 1 — Basic Case
$ Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output: 2
💡 Note: For arr1[0]=4: closest in arr2 is 1, |4-1|=3 > 2 ✓. For arr1[1]=5: closest is 1, |5-1|=4 > 2 ✓. For arr1[2]=8: found 8 in arr2, |8-8|=0 ≤ 2 ✗. Result: 2 elements count.
Example 2 — All Elements Count
$ Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
Output: 2
💡 Note: For arr1[0]=1: closest in arr2 is -3, |1-(-3)|=4 > 3 ✓. For arr1[1]=4: closest is 6, |4-6|=2 ≤ 3 ✗. For arr1[2]=2: closest is -3, |2-(-3)|=5 > 3 ✓. For arr1[3]=3: closest is 6, |3-6|=3 ≤ 3 ✗. Result: 2 elements count.
Example 3 — No Elements Count
$ Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
Output: 1
💡 Note: Only arr1[2]=100 is far enough from all arr2 elements. The others have at least one arr2 element within distance 6.

Constraints

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

Visualization

Tap to expand
Distance Value Between Two Arrays INPUT arr1 = 4 5 8 arr2 = 10 9 1 8 d = 2 Number Line View 1 4 5 8 9 10 arr1 arr2 Distance d=2 means check range [val-2, val+2] for each arr1 element ALGORITHM STEPS 1 Sort arr2 arr2 sorted: [1,8,9,10] Enables binary search 2 For each arr1[i] Binary search for closest element in sorted arr2 3 Check distance If min_diff > d, count++ 4 Process elements arr1[0]=4: closest=1 |4-1|=3 > 2 [OK] arr1[1]=5: closest=8 |5-8|=3 > 2 [OK] arr1[2]=8: closest=8 |8-8|=0 <= 2 [FAIL] FINAL RESULT Elements satisfying condition: 4 min distance = 3 3 > 2 : COUNTED 5 min distance = 3 3 > 2 : COUNTED 8 min distance = 0 0 <= 2 : NOT COUNTED Distance Value 2 Key Insight: Sort arr2 to enable binary search for finding the closest element to each arr1[i]. For each element in arr1, use binary search to find nearest value in arr2, then check if distance > d. Time Complexity: O(n*log(m)) where n=len(arr1), m=len(arr2) | Space: O(1) extra TutorialsPoint - Find the Distance Value Between Two Arrays | Optimal Binary Search Approach
Asked in
Facebook 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~15 min Avg. Time
580 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen