KatInterview

Minimum-Distance Depot Placement on a Grid with Blocked Cells

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchmanhattan-distancemedianpriority-queue

Last updated

Place a depot on a 2D integer grid to minimize total Manhattan distance to all warehouses, avoiding any cell occupied by an obstacle.

Problem

You manage a network of warehouses scattered across a 2D integer grid. You need to pick a single depot location to serve all of them, minimizing the total delivery distance.

Formally, you are given:

  • warehouses: a list of (x, y) integer coordinates representing warehouse positions.
  • obstacles: a list of (x, y) integer coordinates where depots cannot be placed (boulders, restricted zones, etc.).

Choose a depot location D = (x, y) such that:

  • D is not in obstacles
  • The sum of Manhattan distances Σ |x − xᵢ| + |y − yᵢ| over all warehouses is minimized

Return a tuple (min_cost, (x, y)) where min_cost is that minimum total distance and (x, y) is one valid optimal location.

Notes:

  • The depot may share a cell with a warehouse.
  • Obstacles only block where the depot can go — distances are still straight Manhattan, not paths routed around boulders.
  • The grid is unbounded.
  • If multiple locations tie, return any one of them.

Constraints:

  • 1 ≤ |warehouses| ≤ 10⁵
  • 0 ≤ |obstacles| ≤ 10⁴
  • Coordinates fit in a 32-bit integer; use 64-bit accumulators for sums.

Example:

warehouses = [(0,0), (2,0), (1,2)]
obstacles  = [(1,0)]

Unconstrained optimum: (1, 0), total cost = |1-0|+|1-2|+|1-1| + |0-0|+|0-0|+|0-2| = 2 + 2 = 4
But (1, 0) is blocked.
Next best free cell: (1, 1), total cost = 2 + 3 = 5

Output: (5, (1, 1))   # or any other cell with cost 5

What is expected:

Describe and implement an efficient algorithm. Cover:

  1. Why the unconstrained problem reduces to finding coordinate medians.
  2. How to enumerate candidate locations in order of increasing cost when the median is blocked.
  3. Correctness argument, complexity analysis, and key edge cases.

Hints

Hint 1

Manhattan distance splits cleanly into independent x and y terms — the optimal x and y can be found separately, each by minimizing a sum of absolute differences over a 1D list of coordinates.

Hint 2

The function F(v) = Σ|v − cᵢ| is convex and piecewise linear. Its minimum is at any median of the cᵢ values, and moving away from the median in either direction gives a non-decreasing sequence of costs. You can merge those two outward walks (left and right of the median) to get all integers sorted by F(v) lazily.

Hint 3

Once you have two sorted sequences of x-values and y-values (sorted by their individual axis costs), finding the cheapest unblocked (x, y) pair is exactly the 'k-th smallest sum from two sorted arrays' problem — a classic min-heap expansion that terminates after at most |obstacles| + 1 pops.