Best Meeting Point
Hard
Topics
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
(0, 2) costs 6 in total, and nothing costs less. Notice the cheapest cell need not be anybody’s home.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
Input: grid = [[1,1]] Output: 1 Explanation: Two adjacent friends; whichever home they meet at, one of them walks 1.
Example 3
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
- Collect the row index of every friend, and separately the column index of every friend.
- Sort each list. Scanning the grid row by row already produces the rows in order, so only the columns need an explicit sort.
- Take the median of each list.
- 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)import java.util.*;
class Solution {
public int minTotalDistance(int[][] grid) {
List<Integer> rows = new ArrayList<>(), cols = new ArrayList<>();
for (int r = 0; r < grid.length; r++) for (int c = 0; c < grid[r].length; c++) if (grid[r][c] == 1) {
rows.add(r);
cols.add(c);
}
if (rows.isEmpty()) return 0;
Collections.sort(rows);
Collections.sort(cols);
int mr = rows.get(rows.size() / 2), mc = cols.get(cols.size() / 2);
int total = 0;
for (int r : rows) total += Math.abs(r - mr);
for (int c : cols) total += Math.abs(c - mc);
return total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minTotalDistance(vector<vector<int>>& grid) {
vector<int> rows, cols;
for (size_t r = 0; r < grid.size(); r++) for (size_t c = 0; c < grid[r].size(); c++) if (grid[r][c] == 1) {
rows.push_back((int)r);
cols.push_back((int)c);
}
if (rows.empty()) return 0;
sort(rows.begin(), rows.end());
sort(cols.begin(), cols.end());
int mr = rows[rows.size() / 2], mc = cols[cols.size() / 2];
int total = 0;
for (int r : rows) total += abs(r - mr);
for (int c : cols) total += abs(c - mc);
return total;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var minTotalDistance = function(grid) {
const rows = [], cols = [];
for (let r = 0; r < grid.length; r++) {
for (let c = 0; c < grid[r].length; c++) {
if (grid[r][c] === 1) {
rows.push(r);
cols.push(c);
}
}
}
if (!rows.length) return 0;
rows.sort((a, b) => a - b);
cols.sort((a, b) => a - b);
const mr = rows[Math.floor(rows.length / 2)], mc = cols[Math.floor(cols.length / 2)];
let total = 0;
for (const r of rows) total += Math.abs(r - mr);
for (const c of cols) total += Math.abs(c - mc);
return total;
};