hard Best Meeting Point
Problem Statement
You are given m x n matrix containing 1 and 0 digits only, where each 1 represents the home of one friend, return the minimum total travel distance.
The minimal total travel distance is defined as a sum of distances between each friend's house and meeting point. Here, you need to find the meeting point such that it should have minimal distance from the home of each friend.
The distance is calculated as the Manhattan distance, which is the sum of the absolute differences in the horizontal and vertical coordinates (distance(a1, a2) = |a2.x - a1.x| + |a2.y - a1.y|).
Example
Example 1:
- Input:
[[1,0],
[0,1]]
- Expected Output: 2
- Justification: There are two people located at the top-left and bottom-right corners. The best meeting point is either of the two empty cells, each resulting in a total distance of 2.
Example 2:
- Input:
[[1,0,1],
[0,1,0],
[1,0,1]]
- Expected Output: 8
- Justification: The grid has four people at the corners and one in the center. The best meeting points are the four cells adjacent to the center cell (either horizontally or vertically), each resulting in a total distance of 8.
Example 3:
- Input:
[[1,1,0],
[0,0,1],
[0,0,1]]
- Expected Output: 6
- Justification: People are located at the top two corners and the bottom two cells of the rightmost column. The optimal meeting point is the cell in the second row, center, or rightmost column, with a total distance of 6. This point is vertically central and at the horizontal edge, closest to the majority of people.
Try it yourself
Try solving this question here:
✅ Solution Best Meeting Point
Problem Statement
You are given m x n matrix containing 1 and 0 digits only, where each 1 represents the home of one friend, return the minimum total travel distance.
The minimal total travel distance is defined as a sum of distances between each friend's house and meeting point. Here, you need to find the meeting point such that it should have minimal distance from the home of each friend.
The distance is calculated as the Manhattan distance, which is the sum of the absolute differences in the horizontal and vertical coordinates (distance(a1, a2) = |a2.x - a1.x| + |a2.y - a1.y|).
Example
Example 1:
- Input:
[[1,0],
[0,1]]
- Expected Output: 2
- Justification: There are two people located at the top-left and bottom-right corners. The best meeting point is either of the two empty cells, each resulting in a total distance of 2.
Example 2:
- Input:
[[1,0,1],
[0,1,0],
[1,0,1]]
- Expected Output: 8
- Justification: The grid has four people at the corners and one in the center. The best meeting points are the four cells adjacent to the center cell (either horizontally or vertically), each resulting in a total distance of 8.
Example 3:
- Input:
[[1,1,0],
[0,0,1],
[0,0,1]]
- Expected Output: 6
- Justification: People are located at the top two corners and the bottom two cells of the rightmost column. The optimal meeting point is the cell in the second row, center, or rightmost column, with a total distance of 6. This point is vertically central and at the horizontal edge, closest to the majority of people.
Solution
To solve this problem, we leverage the properties of Manhattan distance. Since the distance is the sum of absolute differences along each axis, we can treat the x and y coordinates independently. The optimal meeting point minimizes the sum of horizontal distances for all x coordinates and vertical distances for all y coordinates.
The most effective approach is to find the median of all x and y coordinates of the people on the grid. The median minimizes the sum of absolute differences from a central point. First, we collect all the x and y coordinates of the people, then find their medians. The cell at the median x and median y coordinates is our optimal meeting point. This approach works because in a sorted list of numbers, the median minimizes the sum of absolute differences.
Step-by-step Algorithm
- Initialize two lists,
xCoordsandyCoords, to store the x and y coordinates of people. - Traverse the grid:
- For each cell with a person (1), add its x and y coordinates to
xCoordsandyCoordsrespectively.
- For each cell with a person (1), add its x and y coordinates to
- Sort both
xCoordsandyCoords. - Find the median of
xCoordsandyCoords. If the number of coordinates is even, choose the lower middle value as the median. - Calculate the total Manhattan distance:
- Sum up the absolute differences between each coordinate in
xCoordsand the x median. - Do the same for
yCoordsand the y median.
- Sum up the absolute differences between each coordinate in
- Return the total sum of these distances as the result.
5. Algorithm Walkthrough
Let's take Example 2:
[[1, 0, 1],
[0, 1, 0],
[1, 0, 1]]
-
Collect Coordinates:
- Traverse the grid and collect the x and y coordinates of all cells containing 1.
- Resulting coordinates:
xCoords = [0, 0, 1, 2, 2]yCoords = [0, 2, 1, 0, 2]
-
Sort Coordinates:
- Sort both
xCoordsandyCoordsindependently. - After sorting:
xCoords = [0, 0, 1, 2, 2](already sorted)yCoords = [0, 0, 1, 2, 2](after sorting)
- Sort both
-
Calculate Median:
- For both lists, the median is the middle element (as we have an odd number of elements).
- Median of
xCoords= 1 (middle element) - Median of
yCoords= 1 (middle element)
-
Calculate Total Distance:
- Sum the absolute differences between each coordinate and the median.
- For
xCoords: |0-1| + |0-1| + |1-1| + |2-1| + |2-1| = 1 + 1 + 0 + 1 + 1 = 4 - For
yCoords: |0-1| + |0-1| + |1-1| + |2-1| + |2-1| = 1 + 1 + 0 + 1 + 1 = 4
-
Final Result:
- Total distance = Distance for
xCoords+ Distance foryCoords= 4 + 4 = 8
- Total distance = Distance for
Hence, for the given grid, the minimum total distance to the best meeting point is 8.
Code
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Solution {
// Method to calculate the minimum total distance
public int minTotalDistance(int[][] grid) {
List<Integer> xCoords = new ArrayList<>();
List<Integer> yCoords = new ArrayList<>();
// Collecting x and y coordinates of all people
for (int x = 0; x < grid.length; x++) {
for (int y = 0; y < grid[0].length; y++) {
if (grid[x][y] == 1) {
xCoords.add(x);
yCoords.add(y);
}
}
}
// Calculate minimum distance separately for x and y coordinates
return getMinDistance(xCoords) + getMinDistance(yCoords);
}
// Helper method to compute minimum distance for a list of coordinates
private int getMinDistance(List<Integer> coords) {
Collections.sort(coords);
int i = 0, j = coords.size() - 1, distance = 0;
// Reducing the distance from both ends towards the median
while (i < j) {
distance += coords.get(j--) - coords.get(i++);
}
return distance;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Testing with Example 1
int[][] grid1 = { { 1, 0 }, { 0, 1 } };
System.out.println("Example 1: " + solution.minTotalDistance(grid1));
// Testing with Example 2
int[][] grid2 = { { 1, 0, 1 }, { 0, 1, 0 }, { 1, 0, 1 } };
System.out.println("Example 2: " + solution.minTotalDistance(grid2));
// Testing with Example 3
int[][] grid3 = { { 1, 1, 0 }, { 0, 0, 1 }, { 0, 0, 1 } };
System.out.println("Example 3: " + solution.minTotalDistance(grid3));
}
}
Complexity Analysis
Time Complexity
m and n are the dimensions of the grid, and k is the number of people in the grid. This is due to the initial grid traversal to collect coordinates
Space Complexity
k is the number of people in the grid. This space is used to store the coordinates of the people. In the worst-case scenario, if every cell is occupied, this becomes
🤖 Don't fully get this? Learn it with Claude
Stuck on Best Meeting Point? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Best Meeting Point** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Best Meeting Point** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Best Meeting Point**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Best Meeting Point**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.