Best Meeting Point — LeetCode 296 Python Solution

HardLeetCode PremiumArrayMathMatrixSorting
Problem
#296
Reading time
3 min

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

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

Python solution

Python
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

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 296. Best Meeting Point is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 296. Best Meeting Point?
LeetCode 296. Best Meeting Point is rated Hard on LeetCode.
What topics does LeetCode 296. Best Meeting Point cover?
LeetCode 296. Best Meeting Point is tagged Array, Math, Matrix and Sorting on LeetCode.
Is LeetCode 296. Best Meeting Point a premium problem?
Yes. LeetCode 296. Best Meeting Point is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview