Best Meeting Point

Manhattan distance separates into 1D medians on rows and columns — sum each axis's deviations from the median.

Hard
Time O(m*n) Space O(m + n)
LeetCode
4 min read
matrix median math

Problem#

Given a binary grid where 1 represents a person’s home, return the minimum total Manhattan distance from a meeting point to every home. The meeting point can be any cell.

Examples#

  • [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]]6
  • [[1,1]]1

Constraints#

  • m == grid.length, n == grid[i].length, 1 <= m, n <= 200. At least one 1.

Approach#

Manhattan distance |r - rm| + |c - cm| separates additively across rows and columns. The 1D facility-location optimum is the median. Collect row indices in row-major order (naturally sorted), then column indices in column-major order to keep them sorted; sum deviations from each axis’s median.

Solution#

Best Meeting Point
class Solution {
public:
int minTotalDistance(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<int> rows, cols;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (grid[i][j] == 1) rows.push_back(i);
for (int j = 0; j < n; ++j)
for (int i = 0; i < m; ++i)
if (grid[i][j] == 1) cols.push_back(j);
return medianDist(rows) + medianDist(cols);
}
private:
int medianDist(vector<int>& v) {
int sum = 0, l = 0, r = v.size() - 1;
while (l < r) { sum += v[r--] - v[l++]; }
return sum;
}
};

Editorial#

For 1D points, picking the median minimizes the sum of absolute deviations. The two-pointer trick pairs the smallest with the largest, summing their span — the chosen meeting point lies anywhere between them, which is precisely the median range.

Complexity#

  • Time: O(m*n).
  • Space: O(m + n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.