Optimal Commute: Nearest Transit Distance in a City Grid
DatabricksSoftware Engineer · Technical ScreenLast updated
Tests the ability to solve multi-source shortest path problems on a grid using multi-source Breadth-First Search (BFS). Evaluates graph traversal efficiency, boundary checking, and handling of impassable terrain.
Problem Statement
You are given an m x n 2D grid representing a city map. Each cell in the grid contains one of three characters:
'T': A transit station.'.': An open road that commuters can walk through.'X': An impassable building or obstacle.
Commuters can move in four cardinal directions (up, down, left, right) between adjacent open cells. Each step between adjacent cells takes 1 unit of distance. Commuters cannot move into or through 'X' cells.
Write a function to return an m x n matrix of integers where each cell contains the minimum distance to the nearest transit station 'T'. The rules for the output matrix are:
- The distance for a transit station
'T'is0. - The distance for an impassable cell
'X'is-1. - If an open cell
'.'cannot reach any transit station, its distance is-1.
Function Signature
def find_transit_distances(grid: list[list[str]]) -> list[list[int]]:
pass
Input & Output Format
- Input: A list of lists of strings
gridof sizem x nwhere each character is'T','.', or'X'. - Output: A 2D list of integers of size
m x nrepresenting the shortest distance to a transit station for each cell.
Constraints
m == len(grid)n == len(grid[i])1 <= m, n <= 500- Total cells
m * n <= 250,000 grid[r][c]is one of'T','.', or'X'.
Examples
Example 1
Input:
grid = [
['.', '.', 'T'],
['.', 'X', '.'],
['T', '.', '.']
]
Output:
[
[2, 1, 0],
[1, -1, 1],
[0, 1, 2]
]
Explanation:
(0, 2)and(2, 0)are transit stations, so their distances are0.(1, 1)is an obstacle'X', so its distance is-1.(0, 1)is 1 step from(0, 2), so its distance is1.
Example 2
Input:
grid = [
['X', 'T'],
['.', 'X'],
['.', '.']
]
Output:
[
[-1, 0],
[-1, -1],
[-1, -1]
]
Explanation: The open cells at (1, 0), (2, 0), and (2, 1) are blocked by 'X' and cannot reach the transit station at (0, 1), so their distance is -1.
Edge Cases
- No transit stations present in the grid (all reachable cells should return
-1). - Entire grid consists of transit stations or obstacles.
1 x 1grid.
Hints
Hint 1
Running a separate BFS from every open cell towards the nearest station is too slow and results in O((m * n)^2) time complexity.
Hint 2
Instead of searching from each open cell to find stations, reverse the search direction: start from all transit stations simultaneously.
Hint 3
Initialize a queue with all 'T' coordinates at distance 0 and expand outward level-by-level, updating open cells that have not yet been visited.
Follow-up questions
- How would you adapt your solution if transit stations have different entry delays or if roads have non-uniform traversal costs (e.g., traffic conditions)?
- What changes would be required if the grid is stored across distributed partitions and does not fit in the memory of a single machine?
- Suppose we want to find the single open cell that minimizes the maximum distance to any transit station. How would you solve that efficiently?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.