Best Meeting Point - Problem

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|.

Input & Output

Example 1 — Basic 3x5 Grid
$ Input: grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output: 6
💡 Note: Friends are at (0,0), (0,4), and (2,2). The optimal meeting point is (0,2) with total distance = |0-0|+|0-2| + |0-0|+|4-2| + |2-0|+|2-2| = 2+2+2 = 6
Example 2 — Single Row
$ Input: grid = [[1,1]]
Output: 1
💡 Note: Two friends at (0,0) and (0,1). Meeting at either location gives distance 1. Optimal is anywhere between them.
Example 3 — Single Friend
$ Input: grid = [[1]]
Output: 0
💡 Note: Only one friend, so meeting point is at their location with distance 0

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 200
  • grid[i][j] is either 0 or 1
  • There will be at least one friend in the grid

Visualization

Tap to expand
Best Meeting Point INPUT 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 = Friend's Home Friend Positions: A: (0, 0) B: (0, 4) C: (2, 2) m=3, n=5 grid 3 friends total ALGORITHM STEPS 1 Extract Coordinates Collect row and col positions of all 1s 2 Sort Coordinates rows: [0, 0, 2] cols: [0, 2, 4] 3 Find Medians median_row = 0 median_col = 2 Meeting: (0, 2) 4 Sum Distances A: |0-0|+|0-2| = 2 B: |0-0|+|4-2| = 2 C: |2-0|+|2-2| = 2 Manhattan Distance: |x2-x1| + |y2-y1| FINAL RESULT A M B C = Meeting Point (0,2) = Travel path Distance Calculation: A to M: 2 steps B to M: 2 steps C to M: 2 steps Output: 6 Key Insight: The optimal meeting point minimizes Manhattan distance when it's at the MEDIAN of all coordinates. Row and column can be solved independently - find median of rows and median of columns separately. Time Complexity: O(mn log mn) | Space Complexity: O(mn) - Optimal solution using median property. TutorialsPoint - Best Meeting Point | Optimal Solution (Median Approach)
Asked in
Google 15 Facebook 12 Apple 8 Amazon 6
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen