Empty Lot With the Smallest Total Walk to Every Office Building

Last updated: November 29, 2026

Quick Overview

Given a campus grid where 0 is an empty lot, 1 is an office building and 2 is an obstacle, find the empty lot that minimizes the sum of shortest walking distances (4-directional, avoiding buildings and obstacles) to all buildings, and return that sum or -1 if no lot reaches every building.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given a campus grid where 0 is an empty lot, 1 is an office building and 2 is an obstacle, find the empty lot that minimizes the sum of shortest walking distances (4-directional, avoiding buildings and obstacles) to all buildings, and return that sum or -1 if no lot reaches every building.

A Google onsite Hard grid BFS problem in a campus planning framing. The interviewer checks that you BFS from each building (not from each lot, when buildings are fewer), accumulate distances and reach counts, and prune lots that some building cannot reach.

What the Interviewer Expects
  • Chooses BFS from buildings when they are fewer than empty lots
  • Accumulates total distance and a reach count per lot
  • Requires reach count to equal the number of buildings
  • Prunes by only expanding lots reached by all previous buildings
  • States O(B * mn) time
Key Topics to Cover
Multi-Source BFS
Grid Graphs
Pruning
Shortest Paths
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Why does the Manhattan median trick not work here?
  • What if people may walk through other buildings?
  • The grid is huge but buildings are few and far apart; how would you scale?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: grid with 0 (empty), 1 (building), 2 (obstacle).
  • Walks move through empty lots only; buildings are endpoints, not corridors.
  • Output: the minimum over empty lots of the sum of distances ...
High-Level Design

Without obstacles, the Manhattan median would solve it, but obstacles distort distances, so we need BFS. Run one BFS per building over empty cells, adding each distance into total[r][c] and incremen...


Submit Your Answer
Markdown supported