Ctrl K

Nearest Station in a Straight Line

Easy
A courier stands at (home_x, home_y) on a grid. The array stations lists charging stations: stations[i] = [a, b] is a station at (a, b). Only stations the courier can reach in a straight line count: a station must share the courier's x coordinate or y coordinate (or both, so a station may sit at the very same point). The distance between (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|. Return the index of the qualifying station closest to the courier; on a tie, the smallest index. If no station qualifies, return -1.
Example 1
home_x=5, home_y=2, stations=[[5, 9], [1, 1], [8, 2], [5, 4]] → 3

Stations 0 (same x, distance 7), 2 (same y, distance 3) and 3 (same x, distance 2) can be reached in a straight line. Station 3 is the closest. Station 1 lies on neither line.

Example 2
home_x=4, home_y=4, stations=[[2, 4], [6, 4], [4, 6]] → 0

All three stations are 2 away, so the one with the smallest index wins: 0.

Example 3
home_x=1, home_y=1, stations=[[2, 3], [7, 7]] → -1

No station shares a row or a column with the courier.

Constraints
  • 1 ≤ len(stations) ≤ 10⁴
  • Each stations[i] holds two numbers
  • 1 ≤ home_x, home_y, a, b ≤ 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPair With a Target Sum EasySqueeze Repeats Out of a Sorted Array EasyDrop the Unwanted Value EasySlot on a Sorted Shelf EasyAdd One to a Digit Array Easy
loading Python…
Input
home_x=5, home_y=2, stations=[[5, 9], [1, 1], [8, 2], [5, 4]]
Expected
3

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