Shortest Distance from All Buildings
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 neededProblem
You are given a grid where 0 is empty land you can walk through, 1 is a building, and 2 is an obstacle. You want to build a house on one empty cell so that the sum of its walking distances to **every** building is as small as possible.
Walking moves one step up, down, left or right. You may only step onto empty land, except that the final step into a building is allowed (you cannot walk through a building). The distance to a building is the fewest steps from the house cell into that building.
Return the minimum total distance. If no empty cell can reach all buildings, return -1. The grid contains at least one building.
Examples
Constraints
- 1 <= rows, cols <= 50
- `grid[i][j]` is 0, 1 or 2
- There is at least one building.
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.