Find the Distance Value Between Two Arrays - Problem
Find the Distance Value Between Two Arrays
You are given two integer arrays
The distance value is defined as the count of elements
In simpler terms, for each element in
Example:
If
• Element 4: distances to arr2 are [6, 5, 3, 4] - all > 2 ✓
• Element 5: distances to arr2 are [5, 4, 4, 3] - all > 2 ✓
• Element 8: distances to arr2 are [2, 1, 7, 0] - some ≤ 2 ✗
Result: 2 elements (4 and 5) satisfy the condition.
You are given two integer arrays
arr1 and arr2, along with an integer d representing a distance threshold. Your task is to find the distance value between these two arrays.The distance value is defined as the count of elements
arr1[i] such that there is no element arr2[j] where the absolute difference |arr1[i] - arr2[j]| is less than or equal to d.In simpler terms, for each element in
arr1, check if it's "far enough" (distance > d) from all elements in arr2. Count how many such "isolated" elements exist.Example:
If
arr1 = [4, 5, 8], arr2 = [10, 9, 1, 8], and d = 2:• Element 4: distances to arr2 are [6, 5, 3, 4] - all > 2 ✓
• Element 5: distances to arr2 are [5, 4, 4, 3] - all > 2 ✓
• Element 8: distances to arr2 are [2, 1, 7, 0] - some ≤ 2 ✗
Result: 2 elements (4 and 5) satisfy the condition.
Input & Output
example_1.py — Basic Case
$
Input:
arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
›
Output:
2
💡 Note:
For arr1[0]=4: distances are [6,5,3,4] - all > 2 ✓. For arr1[1]=5: distances are [5,4,4,3] - all > 2 ✓. For arr1[2]=8: distances are [2,1,7,0] - some ≤ 2 ✗. Count = 2.
example_2.py — All Valid
$
Input:
arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
›
Output:
4
💡 Note:
Every element in arr1 is more than distance 3 from all elements in arr2. All 4 elements are counted.
example_3.py — None Valid
$
Input:
arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
›
Output:
1
💡 Note:
Only 100 is far enough from all elements in arr2. Elements 2,1,3 are all within distance 6 of some element in arr2.
Constraints
- 1 ≤ arr1.length, arr2.length ≤ 500
- -1000 ≤ arr1[i], arr2[j] ≤ 1000
- 0 ≤ d ≤ 100
- Elements can be negative
- d can be 0 (only exact matches invalidate)
Visualization
Tap to expand
Understanding the Visualization
1
Map the Territory
Sort arr2 to create an organized map of factory locations: [1,8,9,10]
2
Check Each House
For each potential house location in arr1, use binary search to quickly find nearest factories
3
Measure Distances
Check only the closest neighbors instead of measuring to every single factory
4
Count Safe Houses
If all nearby factories are beyond distance d, the house is safe to buy
Key Takeaway
🎯 Key Insight: By sorting arr2 first, we transform an O(n×m) problem into O(m log m + n log m), using binary search to find closest elements instead of checking every pair.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code