Compute delivery times on a grid
Company: DoorDash
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of graph traversal and shortest-path algorithms, grid-based pathfinding, and data structure selection for representing sparse or large grids within the Coding & Algorithms domain.
Constraints
- 1 <= rows, cols (the grid is non-empty in tests; an empty grid returns []).
- Each cell is exactly one of 'M', 'C', 'X', '.'.
- There may be zero or more warehouses ('M') and zero or more customers ('C').
- Movement is 4-directional (no diagonals); 'X' cells are never entered.
- If a customer cannot be reached from any warehouse, its distance is -1.
Examples
Input: [['M', '.', 'C'], ['.', 'X', '.'], ['.', '.', 'C']]
Expected Output: [[0, 2, 2], [2, 2, 4]]
Explanation: Customer at (0,2) is reached via (0,0)->(0,1)->(0,2) in 2 steps. Customer at (2,2) must detour around the obstacle at (1,1): (0,0)->(1,0)->(2,0)->(2,1)->(2,2), 4 steps.
Input: [['M', 'C']]
Expected Output: [[0, 1, 1]]
Explanation: The customer sits directly next to the warehouse: 1 step.
Input: [['M', 'X', 'C']]
Expected Output: [[0, 2, -1]]
Explanation: The obstacle at (0,1) fully separates the customer from the warehouse, so it is unreachable: -1.
Input: [['C', '.', 'M', '.', 'C']]
Expected Output: [[0, 0, 2], [0, 4, 2]]
Explanation: A single central warehouse serves both customers; each is 2 steps away. Demonstrates a single source reaching multiple customers.
Input: [['M', 'M'], ['C', '.']]
Expected Output: [[1, 0, 1]]
Explanation: Two warehouses; the customer at (1,0) is adjacent to the warehouse at (0,0), giving distance 1 (nearest-source semantics of multi-source BFS).
Input: [['.', '.'], ['.', '.']]
Expected Output: []
Explanation: No customers present, so the result is an empty list.
Input: [['X', 'C'], ['M', 'X']]
Expected Output: [[0, 1, -1]]
Explanation: The customer at (0,1) is walled off by obstacles at (0,0) and (1,1) and cannot reach the warehouse at (1,0): -1.
Hints
- Run ONE breadth-first search seeded with all warehouse cells at distance 0, instead of a separate search per warehouse — this directly yields the distance to the nearest warehouse for every cell.
- Use a visited/distance grid initialized to -1; a cell is unreachable exactly when its distance stays -1 after the BFS completes.
- Treat 'X' cells as walls (never enqueue them). 'M', 'C', and '.' are all traversable.
- After the BFS, scan the grid in row-major order and emit [row, col, dist] for every 'C' cell.
- Follow-up: swap the FIFO queue for a min-heap to handle non-uniform (weighted) road costs — that turns multi-source BFS into multi-source Dijkstra.