Which depot is closest
A last-mile sheet lists every depot as an x, y position on a grid. Pick the depot nearest a delivery point, Manhattan distance.
- Distance is |x1 - x2| + |y1 - y2|, in whole units.
- A tie is broken by whoever comes first in the list.
- With no depots at all return -1.
nearest_depot(depots: list<Point>, x: int, y: int) → int
Where you start
def nearest_depot(depots: list[Point], x: int, y: int) -> int:
Worked examples
| Call | Result |
|---|---|
nearest_depot([Point(x=0, y=0), Point(x=10, y=0), Point(x=3, y=4)], 4, 4) | 2 |
nearest_depot([Point(x=0, y=0), Point(x=2, y=2)], 1, 1) | 0 |
nearest_depot([Point(x=9, y=9)], 0, 0) | 0 |
nearest_depot([], 0, 0) | -1 |
Hint
Track a best index while you walk the list.
Reference solution in Python
def nearest_depot(depots: list[Point], x: int, y: int) -> int:
best, best_dist = -1, float("inf")
for i, p in enumerate(depots):
d = abs(p.x - x) + abs(p.y - y)
if d < best_dist:
best, best_dist = i, d
return best