Choose an Office Site Reachable From Every Building With Least Walking

Last updated: November 29, 2026

Quick Overview

A grid has empty land (0), buildings (1) and obstacles (2). Find an empty cell reachable from every building that minimizes the total walking distance from all buildings, and return that distance or -1 if no cell works.

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

0

0

0 solved


A grid has empty land (0), buildings (1) and obstacles (2). Find an empty cell reachable from every building that minimizes the total walking distance from all buildings, and return that distance or -1 if no cell works.

A well-known style of Meta onsite question that adds obstacles to the meetup problem, so the median trick no longer applies. Framed around siting a new shared facility on a campus layout. Interviewers expect a BFS per building and look for the optimization that restricts each BFS to cells every previous building could reach.

What the Interviewer Expects
  • Run a BFS from each building and accumulate distances per cell
  • Only keep cells reachable from every building
  • Use the decreasing marker trick to prune later BFS runs
  • Restore the input grid or work on a copy
  • Explain why the median approach fails with obstacles
Key Topics to Cover
BFS
Multi-source distances
Pruning
Grid traversal
Shortest path
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
  • How would you parallelize this for a very large campus?
  • If there are far more buildings than empty cells, should you BFS from empty cells instead?
  • What if buildings have different weights?
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
  • Grid up to 50 x 50 with at least one building.
  • Movement is four-directional through empty land only; buildings and obstacles block.
  • Return the minimum total distance over valid cells, or -1....
High-Level Design

Run BFS from each building, adding the distance to total[r][c] for every empty cell it reaches. A cell is valid only if all buildings reach it. Instead of a separate reach counter, decrement visited...


Submit Your Answer
Markdown supported