Best Meeting Point

HardMathmath

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A binary grid grid marks where friends live: 1 is a home and 0 is an empty cell. The friends want to pick one meeting cell (any cell, including a home) that minimizes their total travel distance. Distance is Manhattan distance: from (r1, c1) to (r2, c2) it is abs(r1 - r2) + abs(c1 - c2). Return the minimum possible sum of distances from every home to the meeting cell. The grid contains at least one home. Aim for O(rows * cols) time.

Examples

Input: grid = [[1,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output: 6
Meeting at (0,2) costs 2 + 2 + 2 = 6, and no cell does better.
Input: grid = [[1,1]]
Output: 1
Meeting at either home costs 1.

Constraints

  • 1 <= rows, cols <= 200
  • `grid[i][j]` is 0 or 1
  • There is at least one 1 in `grid`.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More math problems