← Questions
Distance from every cell to the nearest taxi
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's first round (coding), last asked Jan 2026. It tests grids, bfs and multi-source bfs.
A city is a grid. Some cells hold an available taxi (1), the rest are empty (0). Return, for every cell, the distance to the nearest available taxi, moving up, down, left or right.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
nearest_taxi(grid: list[list[int]]) -> list[list[int]]—-1where no taxi is reachable (only possible when there are no taxis or with blocked cells in the follow-up).
Example
[[1, 0, 0],
[0, 0, 0],
[0, 0, 1]] -> [[0, 1, 2],
[1, 2, 1],
[2, 1, 0]]
[[0, 0, 0, 0],
[0, 1, 0, 0]] -> [[2, 1, 2, 3],
[1, 0, 1, 2]]
Constraints
-
1 <= rows, cols <= 1000. - Any number of taxis, including none.
Clarifying questions
- Four directions, or diagonals too? Are some cells blocked?
- What should cells return when there are no taxis?
- Is the grid static, or do taxis move?
What a strong answer covers
- A multi-source BFS: start the queue with every taxi at distance 0 and expand once. O(rows · cols) time and space.
- Why it beats a BFS from each cell (O((rows · cols)^2)) or from each taxi.
- Edge cases: no taxis, every cell a taxi, a single row.
Follow-ups
- Taxis come online, go offline and move over time. How do you keep nearest-taxi answers current without recomputing the whole grid?
- Turn this into a service: riders ask for the nearest available taxi at a location while taxis report positions every few seconds. Discuss a spatial index (geohash or grid cells), searching outward ring by ring, sharding by region, and the trade-off between fresh and consistent locations.
- Distances along real roads instead of a grid.
Where it's asked
- Google · First round: coding · Last asked Jan 202645 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
