KatInterview

Optimal Warehouse Placement to Minimize Total Delivery Distance

Math & Bit ManipulationAuto-graded · 21 test cases
MediumAuto-gradedMath & Bit Manipulationarraysmathsorting

Last 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 either 0 or 1.
  • If there are no 1s in the grid, the minimum total distance is 0.

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?