← Questions

Tallest building between parking lots

0
GoogleCoding

A coding interview question asked at Google. It tests bfs, grid and graphs.

A city block is drawn as a rectangular grid of strings. Each tile is one of:

  • 'P': a parking lot. Its height is fixed at 0.
  • '-': a lot where a building can go. You choose its height (a non-negative integer).
  • 'X': unusable land. Nothing is built there and it imposes no rule.

Zoning rule: any two usable tiles ('P' or '-') that share an edge (up, down, left, right; not diagonal) may differ in height by at most 1.

Implement:

def max_building_height(grid: list[str]) -> int: ...

Return the height of the tallest building that can legally be placed anywhere on the grid, assuming every building is made as tall as the rule allows. Return -1 if some building tile cannot reach any parking lot through usable tiles (its height would be unbounded). If the grid has no building tiles, return 0.

Constraints: 0 <= rows, cols <= 1000; the grid is rectangular. Aim for time linear in the number of tiles.

Example 1

P--
---
--P

Answer: 2. The tiles at (0,2), (1,1) and (2,0) are each two steps from the nearest lot.

Example 2

P-X--
--X-P

Answer: 2. The X column splits the block in two; each half has its own lot, and the farthest building on either side is two steps away.

Example 3

PX-

Answer: -1. The building on the right is walled off from every lot.

Follow-up: also return the full grid of maximum heights.

Clarifying questions

  • Is height measured in whole units, with every height a non-negative integer?
  • Does an 'X' tile break the rule between its neighbours completely?
  • If a region of building tiles has no parking lot, is the answer -1 even if other regions are fine?
  • Can the grid be empty, or have no parking lots at all?

What a strong answer covers

  • Sees the rule as a distance bound: no tile can be higher than its walking distance to the nearest lot. That distance is also reachable for every tile at once.
  • Runs one multi-source BFS from every 'P' over usable tiles. The answer is the largest distance found. That is O(rows x cols).
  • Returns -1 when any '-' tile is never reached, and 0 when there are no building tiles.
  • Uses an iterative queue, not recursion, for a 1000 x 1000 grid.
  • Tests all three examples, an empty grid, a grid with only 'X', and a grid with no lots.

Follow-ups

  • Return the full grid of heights.
  • Diagonal neighbours also count.
  • Neighbours may differ by at most d.
  • New parking lots are added one at a time.

Where it's asked

What it tests

bfs · grid · graphs

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding