Best Meeting Point

Hard

Topics
ArrayMathSortingMatrix

Given an m x n binary grid where each 1 marks the home of a friend, return the minimal total travel distance to some meeting point.

The total travel distance is the sum of the distances from every friend’s home to the meeting point, measured in Manhattan distance: the distance between (p1, p2) and (q1, q2) is |p1 - q1| + |p2 - q2|.

The meeting point may be any cell of the grid, occupied or not.

Example 1

01000110000020010001234
a friend’s homea cheapest meeting cell
Each shaded cell is one of the 3 friends. Travel is counted along the grid, never diagonally, so the cost of a cell is the sum of the row gaps plus the sum of the column gaps. Meeting at (0, 2) costs 6 in total, and nothing costs less. Notice the cheapest cell need not be anybody’s home.
2D grid — one row per line.
Input:  grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output: 6
Explanation: Friends live at (0,0), (0,4) and (2,2). Meeting at (0,2) costs 2 + 2 + 2 = 6, and nothing beats it.

Example 2

01101
a friend’s home
Here the cheapest cell happens to be somebody’s home.
Input:  grid = [[1,1]]
Output: 1
Explanation: Two adjacent friends; whichever home they meet at, one of them walks 1.

Example 3

01010101234
a friend’s home
Input:  grid = [[1,0,1,0,1]]
Output: 4
Explanation: Meeting at the middle friend costs 2 + 0 + 2.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • grid[i][j] is either 0 or 1
  • There is at least one friend in the grid
Editorial — intuition, approach, complexity and pitfalls

Intuition

Manhattan distance adds the row gap and the column gap without mixing them, so the total cost splits cleanly into a row part and a column part. The best meeting row can therefore be chosen without any reference to the columns, and vice versa — what looks like a two-dimensional search is two independent one-dimensional ones.

In one dimension the question is: given points on a line, which point minimises the sum of absolute distances to all of them? The answer is the median. The reason is worth seeing: standing anywhere, taking one step towards the side holding more points reduces the total by the difference in counts. The total stops improving exactly when the two sides are balanced, which is the median.

Note this is the median, not the mean. The mean minimises squared distance, and on [0, 0, 10] the two differ — the mean sits at 3.33 for a total of 13.3, the median at 0 for a total of 10.

Approach

  1. Collect the row index of every friend, and separately the column index of every friend.
  2. Sort each list. Scanning the grid row by row already produces the rows in order, so only the columns need an explicit sort.
  3. Take the median of each list.
  4. Sum |row - medianRow| over the rows and |col - medianCol| over the columns, and add the two totals.

Walkthrough

grid = [[1,0,0,0,1],
        [0,0,0,0,0],
        [0,0,1,0,0]]

friends at (0,0) (0,4) (2,2)

rows    [0, 0, 2]   median 0
cols    [0, 2, 4]   median 2

row cost  |0-0| + |0-0| + |2-0| = 2
col cost  |0-2| + |2-2| + |4-2| = 4

answer 6   (the meeting cell is (0,2), which nobody lives in)

Complexity

  • Time — O(m * n): one pass to collect the coordinates. The column sort is O(k log k) in the number of friends, which never exceeds the cell count.
  • Space — O(k): one row index and one column index per friend.

Common Pitfalls

  • Using the mean instead of the median. It is the natural guess and it is wrong whenever the friends are unevenly spread.
  • Searching every cell as a candidate meeting point and summing distances from scratch. That is O((m*n)²) and times out on a 200x200 grid.
  • Collecting the columns in grid order and assuming they are sorted. Rows come out sorted from a row-major scan, columns do not.
  • With an even number of friends either middle value is optimal, so there is no need to average them — and averaging can land between cells.

Full Solution — all languages

class Solution:
    def minTotalDistance(self, grid):
        rows, cols = [], []
        for r, row in enumerate(grid):
            for c, cell in enumerate(row):
                if cell == 1:
                    rows.append(r)
                    cols.append(c)
        if not rows:
            return 0
        rows.sort()
        cols.sort()
        mid_row = rows[len(rows) // 2]
        mid_col = cols[len(cols) // 2]
        return sum(abs(r - mid_row) for r in rows) + sum(abs(c - mid_col) for c in cols)
SensAI
Beta
Tap the mic to stop voice mode