Optimal Warehouse Placement to Minimize Total Delivery Distance
Math & Bit ManipulationAuto-graded · 21 test casesLast updated
Find the minimum cumulative Manhattan distance from a single target point to all target locations in a 2D grid.
Given a 2D grid grid of size $M \times N$ containing only 0s and 1s, each 1 represents a customer location requiring delivery.
You need to place a central distribution warehouse at a cell $(r, c)$ in the grid such that the sum of Manhattan distances from all customer locations to this warehouse is minimized.
The warehouse can be built on any grid cell, including cells that already contain a 1.
The Manhattan distance between two cells $(r_1, c_1)$ and $(r_2, c_2)$ is defined as: $$\text{dist}((r_1, c_1), (r_2, c_2)) = |r_1 - r_2| + |c_1 - c_2|$$
Return the minimum possible total Manhattan distance from all customer locations to the warehouse.
Constraints
- $M == \text{len}(grid)$
- $N == \text{len}(grid[r])$
- $1 \le M, N \le 200$
grid[r][c]is either0or1.- If there are no
1s in the grid, the minimum total distance is0.
Examples
Example 1
Input: minimize_total_distance([[0, 1, 0], [0, 0, 0], [1, 0, 1]])
Output: 4
Example 2
Input: minimize_total_distance([[0, 0], [0, 0]])
Output: 0
Hints
Hint 1
Manhattan distance splits independently into horizontal and vertical components: |r1 - r2| + |c1 - c2|.
Hint 2
Because the dimensions are independent, you can find the optimal row coordinate and column coordinate separately.
Hint 3
For a set of 1D coordinates, which central value minimizes the sum of absolute differences to all points?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks for a grid location $(R, C)$ that minimizes:
$$\sum_{i=1}^{K} (|r_i - R| + |c_i - C|)$$
where $(r_i, c_i)$ are the coordinates of all $K$ customer locations (1s).
Notice that the sum of Manhattan distances can be decoupled into two independent 1D problems: $$\sum_{i=1}^{K} |r_i - R| + \sum_{i=1}^{K} |c_i - C|$$
To minimize $\sum_{i=1}^{K} |x_i - X|$ for a set of numbers $x_1, x_2, \dots, x_K$, the optimal choice for $X$ is the median of the values.
- Collect the row indices
rowsand column indicescolsof all cells containing1. - Sort
rowsandcolsindependently. - Select the median element for each list:
median_row = rows[K // 2]median_col = cols[K // 2]
- Compute the total Manhattan distance from all points to $(median_row, median_col)$.
Complexity
- Time Complexity: $\mathcal{O}(M \times N + K \log K)$, where $M \times N$ is the number of grid cells and $K$ is the count of
1s. Collecting coordinates takes $\mathcal{O}(M \times N)$ and sorting takes $\mathcal{O}(K \log K)$. (Note: scanning row-by-row and column-by-column directly yields sorted lists in $\mathcal{O}(M \times N)$ time). - Space Complexity: $\mathcal{O}(K)$ to store the coordinate lists.
from typing import List
def minimize_total_distance(grid: List[List[int]]) -> int:
rows = []
cols = []
for r, row in enumerate(grid):
for c, val in enumerate(row):
if val == 1:
rows.append(r)
cols.append(c)
if not rows:
return 0
rows.sort()
cols.sort()
median_row = rows[len(rows) // 2]
median_col = cols[len(cols) // 2]
return sum(abs(r - median_row) + abs(c - median_col) for r, c in zip(rows, cols))