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 Problem OverviewInput: Binary Grid111Friends at (0,0), (0,4), (2,2)Find optimalmeeting pointProcess: Use MedianRows: [0,0,2] → median = 0Cols: [0,4,2] → median = 2Optimal point: (0,2)Manhattan distance minimizedOutput: Distance6Total distance fromall friends to (0,2)Distance calculation: |0-0|+|0-2| + |0-0|+|4-2| + |2-0|+|2-2| = 2+2+2 = 6🎯 Manhattan Distance = |x₁-x₂| + |y₁-y₂|
Understanding the Visualization
1
Input
Binary grid with 1s marking friend locations
2
Process
Find optimal meeting point using median coordinates
3
Output
Return minimum total travel distance
Key Takeaway
🎯 Key Insight: The optimal meeting point is at the intersection of median row and median column coordinates
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