Drill

ProblemsTypeScript › logistics

Which depot is closest

mediumlogisticsTypeScript

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

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

Solve it in the editor →

Where you start

function nearestDepot(depots: Point[], x: number, y: number): number {
  
}

Worked examples

CallResult
nearestDepot([{"x":0,"y":0},{"x":10,"y":0},{"x":3,"y":4}], 4, 4)2
nearestDepot([{"x":0,"y":0},{"x":2,"y":2}], 1, 1)0
nearestDepot([{"x":9,"y":9}], 0, 0)0
nearestDepot([], 0, 0)-1

Hint

Track a best index while you walk the list.

Reference solution in TypeScript
function nearestDepot(depots: Point[], x: number, y: number): number {
  let best = -1;
  let bestDist = Infinity;
  for (let i = 0; i < depots.length; i++) {
    const d = Math.abs(depots[i].x - x) + Math.abs(depots[i].y - y);
    if (d < bestDist) {
      bestDist = d;
      best = i;
    }
  }
  return best;
}

The same problem in another language

More logistics problems in TypeScript