Minimum-Distance Depot Placement on a Grid with Blocked Cells
Heaps, Sorting & SearchModel answerLast 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:
Dis not inobstacles- 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:
- Why the unconstrained problem reduces to finding coordinate medians.
- How to enumerate candidate locations in order of increasing cost when the median is blocked.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why the problem separates by axis
Manhattan distance is additive across dimensions:
Σ (|x − xᵢ| + |y − yᵢ|) = Σ|x − xᵢ| + Σ|y − yᵢ|
= Fx(x) + Fy(y)
Because Fx depends only on x and Fy only on y, minimizing the sum is equivalent to minimizing each function independently. This is the core insight that makes the problem tractable.
Unconstrained optimum: the 1D median
F(v) = Σ|v − cᵢ| is a convex piecewise-linear function minimized at the median of the cᵢ. With an even count there is a whole interval of tied medians; any integer in that interval works equally well.
Evaluating F(v) efficiently uses prefix sums on sorted coordinates. If k values are ≤ v:
F(v) = v·k − prefix[k] + (prefix[n] − prefix[k]) − v·(n − k)
This gives O(log n) per query (binary search for k, then O(1) arithmetic).
Without obstacles, the answer is (median_x, median_y) at cost Fx(median_x) + Fy(median_y).
Handling blocked cells: best-first search over axis index pairs
When the median cell is an obstacle, the next-best cells live at coordinates just outside it on one or both axes. The key observation: walking outward from a 1D median in either direction produces a non-decreasing sequence of costs. Merging the left and right walks with two pointers gives all integers sorted by axis cost, generated lazily.
Call these sorted sequences X[0], X[1], … (by increasing Fx) and Y[0], Y[1], … (by increasing Fy). The pair costs form a matrix that is non-decreasing along every row and column — exactly the shape exploited by the k-smallest-pair-sums heap algorithm:
- Push index pair
(0, 0)onto a min-heap keyed byFx(X[i]) + Fy(Y[j]). - Pop the cheapest pair
(i, j). - If
(X[i], Y[j])is not an obstacle, return it. - Otherwise push
(i+1, j)and(i, j+1)(if not already seen), then go to step 2.
The first free cell popped is provably optimal: every earlier pop had lower or equal total cost, and all of those were obstacles.
Termination: each non-returning pop corresponds to a distinct obstacle cell, so the loop runs at most |obstacles| + 1 times.
Complexity
| Phase | Cost |
|---|---|
| Sort coordinates, build prefix sums | O(n log n) |
| Heap pops | ≤ t + 1, where t = |obstacles| |
| Per heap operation | O(log t) heap + O(log n) cost eval |
| Lazy axis list entries generated | O(t) |
- Time: O(n log n + t (log n + log t))
- Space: O(n + t)
A simpler fallback: the optimal depot must use one of the t+1 cheapest x-values and one of the t+1 cheapest y-values. Brute-forcing all (t+1)² pairs costs O(n log n + t² log n). Fine for small t; the heap version is strictly better in general.
Common mistakes
- Confusing path distance with placement cost. Obstacles block the depot location, not the delivery route. Using BFS shortest paths is a category error here.
- Off-by-one on the median index. For
ncoordinates, the lower median is at index(n-1)//2. Both medians of an even-length list are valid starting points. - Forgetting duplicate coordinates. Duplicate warehouses must be counted with multiplicity in the prefix sums. Duplicate obstacles should be deduplicated into a set.
- Integer overflow. With 10⁵ warehouses at coordinates up to ~2×10⁹, a single axis sum can reach ~2×10¹⁴. Use 64-bit integers.
Edge cases
- Median not blocked: the heap returns on the very first pop — call this out explicitly.
- Dense obstacle cluster around the median: the heap walks outward until it finds a gap; correctness is guaranteed because the tree of (i, j) pairs is infinite and obstacles are finite.
- No warehouses: every location costs 0; return the origin if it is free, otherwise the first non-obstacle cell near it.
Python implementation
import bisect
import heapq
from typing import List, Tuple
class AxisCost:
"""
Wraps a list of 1D coordinates and provides:
- cost(v): O(log n) evaluation of F(v) = sum|v - c|
- get(i): the i-th integer sorted by increasing F, generated lazily
"""
def __init__(self, coords: List[int]):
self.c = sorted(coords)
n = len(self.c)
# prefix[k] = sum of the k smallest coordinates
self.pre = [0] * (n + 1)
for idx, v in enumerate(self.c):
self.pre[idx + 1] = self.pre[idx] + v
# start at a median
median = self.c[(n - 1) // 2] if n else 0
self._order = [median]
self._costs = [self.cost(median)]
self._lo = median - 1 # next candidate walking left
self._hi = median + 1 # next candidate walking right
def cost(self, v: int) -> int:
n = len(self.c)
k = bisect.bisect_right(self.c, v) # coords <= v
return v * k - self.pre[k] + (self.pre[n] - self.pre[k]) - v * (n - k)
def get(self, i: int) -> Tuple[int, int]:
"""Return (value, cost) of the i-th cheapest integer."""
while len(self._order) <= i:
cl = self.cost(self._lo)
ch = self.cost(self._hi)
if cl <= ch:
self._order.append(self._lo)
self._costs.append(cl)
self._lo -= 1
else:
self._order.append(self._hi)
self._costs.append(ch)
self._hi += 1
return self._order[i], self._costs[i]
def optimal_depot(
warehouses: List[Tuple[int, int]],
obstacles: List[Tuple[int, int]],
) -> Tuple[int, Tuple[int, int]]:
"""Return (min_total_distance, (x, y)) where (x, y) is not an obstacle."""
ax = AxisCost([w[0] for w in warehouses])
ay = AxisCost([w[1] for w in warehouses])
blocked = {(ox, oy) for ox, oy in obstacles}
def pair_cost(i: int, j: int) -> int:
return ax.get(i)[1] + ay.get(j)[1]
heap = [(pair_cost(0, 0), 0, 0)]
seen = {(0, 0)}
while heap:
d, i, j = heapq.heappop(heap)
x = ax.get(i)[0]
y = ay.get(j)[0]
if (x, y) not in blocked:
return d, (x, y)
for ni, nj in ((i + 1, j), (i, j + 1)):
if (ni, nj) not in seen:
seen.add((ni, nj))
heapq.heappush(heap, (pair_cost(ni, nj), ni, nj))
raise RuntimeError("no free cell found — obstacles must be finite")
# Quick smoke test
if __name__ == "__main__":
cost, loc = optimal_depot([(0, 0), (2, 0), (1, 2)], [(1, 0)])
assert cost == 5, cost # (1,0) blocked; next best costs 5
print(f"cost={cost}, location={loc}")
What a strong answer demonstrates
- Immediately recognizing axis separability and connecting it to the 1D median.
- Framing the blocked-cell case as k-smallest-pair-sums and bounding heap work by
|obstacles|. - Giving the O(n log n + t log(n + t)) complexity rather than hand-waving "efficient."
- Calling out the fast path (unblocked median) and the overflow risk before being asked.