← Applied intuition Interview Insights
I knew the base problem so I started coding pretty confidently, which was a mistake.
Run BFS from each building to compute the total distance to all buildings for every reachable empty cell, tracking the number of buildings that can reach each cell. Then, iterate over all cells (including building cells) that are reachable from all buildings and find the minimum total distance. If no such cell exists, return -1.
Pro tip: Clarify the twist early: building cells are valid candidates, so you must consider them in the final scan. Also, mention that you can optimize by only considering cells that are reachable from all buildings, and use a visited matrix per BFS to avoid revisiting cells.
Restate the problem: find a cell (0, 1, or 2? Actually 2 is obstacle, so only 0 and 1) to place a house minimizing sum of BFS distances to all buildings. Note the twist: building cells (1) are also valid placement candidates. Clarify that obstacles (2) cannot be placed on.
For each building, perform BFS to compute distances to all reachable cells. Maintain a total distance array and a reach count array. Only cells reachable from all buildings are valid candidates.
When scanning for the minimum total distance, include cells that are originally buildings (value 1) as well as empty lands (0). Ensure that building cells are not treated as obstacles during BFS from other buildings.
After all BFS runs, iterate over all cells (0 and 1) that have reach count equal to the number of buildings. Track the minimum total distance. If none found, return -1.
Discuss time complexity: O(B * m * n) where B is number of buildings. Space complexity: O(m * n). Mention edge cases: no buildings, no empty cells, disconnected components.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.