Magicsheet logo

Find the Distance Value Between Two Arrays

Easy
72.8%
Updated 6/1/2025

Find the Distance Value Between Two Arrays

What is this problem about?

The Find the Distance Value Between Two Arrays interview question asks you to count how many elements in the first array (arr1) are "far enough" from every element in the second array (arr2). Specifically, an element xarr1x \in arr1 contributes to the count if for every element yarr2y \in arr2, the absolute difference xy|x - y| is strictly greater than a given value d.

Why is this asked in interviews?

Companies like Uber and Bloomberg use the Find the Distance Value Between Two Arrays coding problem to see if you can optimize a double-loop simulation. While the brute-force approach is O(NM)O(N \cdot M), the sorted nature of differences allows for an O(NlogM)O(N \log M) solution using Binary Search. It evaluations your ability to handle inequalities efficiently.

Algorithmic pattern used

This problem is best solved using Sorting and Binary Search.

  1. Sort: Sort the second array arr2.
  2. Iterate: For each element xx in arr1:
  • Find the closest element to xx in the sorted arr2 using binary search (finding the insertion point).
  • Check if the absolute difference between xx and its immediate neighbors in the sorted arr2 is greater than d.
  1. Count: If the condition holds for xx, increment the distance value counter.

Example explanation

arr1 = [4, 5, 8], arr2 = [10, 9, 1, 8], d = 2

  1. Sort arr2: [1, 8, 9, 10].
  2. Check x=4x=4: Closest in arr2 are 1 and 8. Differences: 41=3,48=4|4-1|=3, |4-8|=4. Both >2> 2. OK.
  3. Check x=5x=5: Closest are 1 and 8. Differences: 51=4,58=3|5-1|=4, |5-8|=3. Both >2> 2. OK.
  4. Check x=8x=8: 88 is in arr2. Difference 88=0|8-8|=0. 020 \leq 2. FAIL. Result: 2.

Common mistakes candidates make

  • Brute Force: Sticking with nested loops for large constraints, leading to Time Limit Exceeded (TLE) errors.
  • Binary Search Errors: Failing to check both elements surrounding the insertion point in the sorted array.
  • Absolute Value: Forgetting to use absolute differences, leading to logic errors with negative results.

Interview preparation tip

When checking if a value satisfies a condition against "all elements" of another array, always consider if sorting that second array allows you to only check the "worst case" (the closest element). This is a common Sorting interview pattern.

Similar Questions