KatInterview

296. Best Meeting Point

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for a meeting point (x, y) that minimizes the total Manhattan distance to all friends' houses. The friends' houses are marked by 1s in a binary grid. The total travel distance is the sum of Manhattan distances from each friend's house to the meeting point.

Solution

Best Meeting Point in Python

class Solution:
    def minTotalDistance(self, grid: List[List[int]]) -> int:
        if not grid or not grid[0]:
            return 0
            
        m, n = len(grid), len(grid[0])
        rows = []
        cols = []

        # Collect row coordinates. Since we iterate row by row,
        # the 'rows' list will be sorted.
        for r in range(m):
            for c in range(n):
                if grid[r][c] == 1:
                    rows.append(r)

        # Collect column coordinates. Since we iterate column by column,
        # the 'cols' list will be sorted.
        for c in range(n):
            for r in range(m):
                if grid[r][c] == 1:
                    cols.append(c)

        total_distance = 0

        # Calculate the sum of distances to the median for rows.
        # For a sorted list, the sum of distances to the median is the
        # sum of differences between symmetric elements.
        i, j = 0, len(rows) - 1
        while i < j:
            total_distance += rows[j] - rows[i]
            i += 1
            j -= 1
        
        # Calculate the sum of distances to the median for columns.
        i, j = 0, len(cols) - 1
        while i < j:
            total_distance += cols[j] - cols[i]
            i += 1
            j -= 1
        
        return total_distance

Best Meeting Point in Java

class Solution {
    public int minTotalDistance(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int m = grid.length;
        int n = grid[0].length;

        List<Integer> rows = new ArrayList<>();
        List<Integer> cols = new ArrayList<>();

        // Collect row coordinates. Since we iterate row by row,
        // the 'rows' list will be sorted.
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    rows.add(i);
                }
            }
        }

        // Collect column coordinates. Since we iterate column by column,
        // the 'cols' list will be sorted.
        for (int j = 0; j < n; j++) {
            for (int i = 0; i < m; i++) {
                if (grid[i][j] == 1) {
                    cols.add(j);
                }
            }
        }

        int totalDistance = 0;

        // Calculate the sum of distances to the median for rows.
        // For a sorted list, the sum of distances to the median is the
        // sum of differences between symmetric elements.
        int i = 0;
        int j = rows.size() - 1;
        while (i < j) {
            totalDistance += rows.get(j) - rows.get(i);
            i++;
            j--;
        }

        // Calculate the sum of distances to the median for columns.
        i = 0;
        j = cols.size() - 1;
        while (i < j) {
            totalDistance += cols.get(j) - cols.get(i);
            i++;
            j--;
        }

        return totalDistance;
    }
}

Best Meeting Point in C++

class Solution {
public:
    int minTotalDistance(vector<vector<int>>& grid) {
        if (grid.empty() || grid[0].empty()) {
            return 0;
        }
        int m = grid.size();
        int n = grid[0].size();
        
        vector<int> rows;
        vector<int> cols;
        
        // Collect row coordinates. Since we iterate row by row,
        // the 'rows' list will be sorted.
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 1) {
                    rows.push_back(i);
                }
            }
        }
        
        // Collect column coordinates. Since we iterate column by column,
        // the 'cols' list will be sorted.
        for (int j = 0; j < n; ++j) {
            for (int i = 0; i < m; ++i) {
                if (grid[i][j] == 1) {
                    cols.push_back(j);
                }
            }
        }
        
        int totalDistance = 0;
        
        // Calculate the sum of distances to the median for rows.
        // For a sorted list, the sum of distances to the median is the
        // sum of differences between symmetric elements.
        int i = 0, j = rows.size() - 1;
        while (i < j) {
            totalDistance += rows[j] - rows[i];
            i++;
            j--;
        }
        
        // Calculate the sum of distances to the median for columns.
        i = 0;
        j = cols.size() - 1;
        while (i < j) {
            totalDistance += cols[j] - cols[i];
            i++;
            j--;
        }
        
        return totalDistance;
    }
};

Best Meeting Point in TypeScript

function minTotalDistance(grid: number[][]): number {
    if (!grid || grid.length === 0 || grid[0].length === 0) {
        return 0;
    }
    const m = grid.length;
    const n = grid[0].length;

    const rows: number[] = [];
    const cols: number[] = [];

    // Collect row coordinates. Since we iterate row by row,
    // the 'rows' list will be sorted.
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (grid[i][j] === 1) {
                rows.push(i);
            }
        }
    }

    // Collect column coordinates. Since we iterate column by column,
    // the 'cols' list will be sorted.
    for (let j = 0; j < n; j++) {
        for (let i = 0; i < m; i++) {
            if (grid[i][j] === 1) {
                cols.push(j);
            }
        }
    }

    let totalDistance = 0;

    // Calculate the sum of distances to the median for rows.
    // For a sorted list, the sum of distances to the median is the
    // sum of differences between symmetric elements.
    let i = 0;
    let j = rows.length - 1;
    while (i < j) {
        totalDistance += rows[j] - rows[i];
        i++;
        j--;
    }

    // Calculate the sum of distances to the median for columns.
    i = 0;
    j = cols.length - 1;
    while (i < j) {
        totalDistance += cols[j] - cols[i];
        i++;
        j--;
    }

    return totalDistance;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.