Best Meeting Point Problem
Description
LeetCode Problem 296.
Given an m x n binary grid grid where each 1 marks the home of one friend, return the minimal total travel distance.
The total travel distance is the sum of the distances between the houses of the friends and the meeting point.
The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
Example 1:

Input: grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output: 6
Explanation: Given three friends living at (0,0), (0,4), and (2,2).
The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal.
So return 6.
Example 2:
Input: grid = [[1,1]]
Output: 1
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 200grid[i][j]is either0or1.- There will be at least two friends in the
grid.
Solution
Approach: Medians of Rows and Columns
The Manhattan distance is |row difference| + |column difference|, so the total travel distance splits into two independent sums: the sum of row distances and the sum of column distances. We can choose the meeting row and the meeting column separately.
In one dimension, the point that minimizes the sum of distances to a set of points is the median. To see why, imagine standing somewhere with more points on your left than on your right: stepping left shortens more distances than it lengthens. The total only stops improving when the points are balanced on both sides, which is at the median. With an even count, any point between the two middle values is equally good, so taking values[len / 2] works in every case.
So:
- Collect the row of every home. Scanning the grid row by row gives them already sorted.
- Collect the column of every home. Scanning column by column gives them sorted too, without a sort call.
- Add up the distances of the rows to their median and of the columns to their median.
In Example 1, the homes are in rows 0, 0, 2 (median 0) and columns 0, 2, 4 (median 2), so the total is (0 + 0 + 2) + (2 + 0 + 2) = 6.
Note that the meeting point may be a home or any empty cell: the problem places no restriction on it.
Complexity: O(mn) time to scan the grid twice. O(mn) space in the worst case for the row and column lists.
class Solution:
def minTotalDistance(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
# Rows and columns of the homes, each in sorted order (scan by rows, then by columns).
rows = [i for i in range(m) for j in range(n) if grid[i][j] == 1]
cols = [j for j in range(n) for i in range(m) if grid[i][j] == 1]
def distance_to_median(values: List[int]) -> int:
median = values[len(values) // 2]
return sum(abs(v - median) for v in values)
# The x and y parts of the Manhattan distance can be minimized separately.
return distance_to_median(rows) + distance_to_median(cols)