A warehouse routing drone hovers at a fixed grid position (x, y) inside a distribution center whose overhead rail network only runs along rows and columns. The ceiling holds a list of n supply beacons, numbered 0 through n-1 in the order they are given; beacon i sits at grid position (a_i, b_i).
The drone's rail carriage can dock directly at beacon i only when the beacon lies exactly on the drone's current row or column, i.e. only when a_i == x or b_i == y. Among every beacon that qualifies this way, the drone must select the one that minimizes travel distance, where distance is the Manhattan distance |x - a_i| + |y - b_i|. If two or more qualifying beacons tie for the smallest distance, the drone always selects the one with the smaller index. If no beacon qualifies at all, the drone reports -1.
Given the drone's position and the beacon list, determine the index of the beacon the drone should dock at (or -1 if none qualifies).
Example 1
Input
5 5 3 5 9 2 5 5 5
Expected
2
Explanation
The drone is at (5,5). Beacon 0 is (5,9): shares x=5, distance |5-5|+|9-5|=4. Beacon 1 is (2,5): shares y=5, distance |2-5|+|5-5|=3. Beacon 2 is (5,5): shares both coordinates, distance |5-5|+|5-5|=0. All three beacons qualify, and beacon 2 has the smallest distance (0), so the answer is 2.
Example 2
Input
0 0 2 1 2 3 4
Expected
-1
Explanation
The drone is at (0,0). Beacon 0 is (1,2): its x (1) differs from the drone's x (0) and its y (2) differs from the drone's y (0), so it does not qualify. Beacon 1 is (3,4): likewise neither coordinate matches, so it does not qualify either. Since no beacon shares the drone's row or column, the answer is -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →