Leetcode #296: Best Meeting Point
In this guide, we solve Leetcode #296 Best Meeting Point in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Array, Math, Matrix, Sorting
Intuition
Sorting reveals structure that is hard to see in the original order.
Once sorted, a linear scan is usually enough to compute the answer.
Approach
Sort the data and sweep through it while maintaining a small state.
This keeps the logic straightforward and reliable.
Steps:
- Sort the data.
- Scan in order while maintaining state.
- Update the best answer.
Example
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.
Python Solution
class Solution:
def minTotalDistance(self, grid: List[List[int]]) -> int:
def f(arr, x):
return sum(abs(v - x) for v in arr)
rows, cols = [], []
for i, row in enumerate(grid):
for j, v in enumerate(row):
if v:
rows.append(i)
cols.append(j)
cols.sort()
i = rows[len(rows) >> 1]
j = cols[len(cols) >> 1]
return f(rows, i) + f(cols, j)
Complexity
The time complexity is O(n log n). The space complexity is O(1) to O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.