Ctrl K

Nearest Pair of Sensors

Hard
A field holds n sensors: sensor i stands at the point (xs[i], ys[i]). The distance between two sensors is measured in city blocks: |x₁ - x₂| + |y₁ - y₂|. Find the pair of sensors i < j with the smallest distance and return [i, j]. If several pairs tie, return the lexicographically smallest one: the smaller i, and for equal i the smaller j. Two sensors may stand at the same point. Trying all pairs in O(n²) is too slow for large n.
Example 1
xs=[0, 4, 2, 5], ys=[3, 1, 2, 4] → [0, 2]

Sensors 0 and 2: |0 - 2| + |3 - 2| = 3. Pair (1, 2) also gives 3, and every other pair is farther. Of the two pairs at distance 3, [0, 2] is lexicographically smaller.

Example 2
xs=[1, 3, 1], ys=[2, 0, 2] → [0, 2]

Sensors 0 and 2 stand at the same point, so their distance is 0.

Example 3
xs=[2, 0], ys=[0, 2] → [0, 1]
Constraints
  • 2 ≤ n = len(xs) = len(ys) ≤ 10⁵
  • 0 ≤ xs[i], ys[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDrop One Point HardNearest Points to the Base MediumBest View for a Turning Camera HardCorner Pairs With No One Between HardClean Rectangle on Pins Hard
loading Python…
Input
xs=[0, 4, 2, 5], ys=[3, 1, 2, 4]
Expected
[0, 2]

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.