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: 4
💡 Note: All elements in arr1 are far enough from all elements in arr2. Minimum distances are all > 3, so all 4 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: Count arr1 elements far from ALL arr2 elementsarr1:458✓ Count✓ Count✗ Skiparr2:10918d = 2 (maximum allowed distance)Element 4: closest is 1, |4-1|=3 > 2 ✓Element 5: closest is 1, |5-1|=4 > 2 ✓Element 8: found exact match, |8-8|=0 ≤ 2 ✗Result: 2
Understanding the Visualization
1
Input Arrays
arr1=[4,5,8], arr2=[10,9,1,8], d=2
2
Check Each Element
For each arr1[i], find if any arr2[j] satisfies |arr1[i]-arr2[j]| ≤ d
3
Count Valid
Count elements that are far from ALL arr2 elements
Key Takeaway
🎯 Key Insight: Each arr1 element must be far from its CLOSEST arr2 element to count
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