Drill

ProblemsPython › logistics

Which depot is closest

mediumlogisticsPython

A last-mile sheet lists every depot as an x, y position on a grid. Pick the depot nearest a delivery point, Manhattan distance.

nearest_depot(depots: list<Point>, x: int, y: int) → int

Solve it in the editor →

Where you start

def nearest_depot(depots: list[Point], x: int, y: int) -> int:
    

Worked examples

CallResult
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

The same problem in another language

More logistics problems in Python