Choose fastest transportation mode on city grid
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to model constrained grid movement and perform weighted shortest-path optimization, covering skills in graph traversal, pathfinding, and multi-criteria comparison of time and cost.
Constraints
- 1 <= number of rows, number of columns <= 200
- grid contains exactly one 'S' and exactly one 'D'
- Each grid cell is one of 'S', 'D', 'X', '1', '2', '3', or '4'
- costPerBlock.length == 4 and timePerBlock.length == 4
- 0 <= costPerBlock[i], timePerBlock[i] <= 10^6
Examples
Input: ([['3', '3', 'S', '2', 'X'], ['3', '1', '1', '2', 'X'], ['3', '1', '1', '2', '2'], ['3', '1', '1', '1', 'D'], ['3', '3', '3', '3', '4'], ['4', '4', '4', '4', '4']], [0, 1, 3, 2], [3, 2, 1, 1])
Expected Output: 2
Explanation: Mode 1 reaches D in 5 moves, so time = 5 * 3 = 15. Mode 2 also reaches D in 5 moves, so time = 5 * 2 = 10. Modes 3 and 4 cannot reach D. Therefore mode 2 is best.
Input: ([['S', '1', 'D'], ['2', '2', '2'], ['X', 'X', 'X']], [5, 1, 7, 9], [2, 1, 3, 4])
Expected Output: 2
Explanation: Mode 1 uses the top row in 2 moves, so time = 4 and cost = 10. Mode 2 uses the second row in 4 moves, so time = 4 and cost = 4. Since times tie, choose the cheaper mode 2.
Input: ([['S', 'D']], [5, 1, 4, 3], [3, 1, 1, 4])
Expected Output: 2
Explanation: Since D is adjacent to S, every mode can reach the destination in exactly 1 move. Modes 2 and 3 both have the minimum time of 1, but mode 2 has lower cost.
Input: ([['S', 'X'], ['X', 'D']], [1, 1, 1, 1], [1, 1, 1, 1])
Expected Output: -1
Explanation: S and D are separated by roadblocks, so no transportation mode can reach the destination.
Input: ([['S', '1', '1', '1', 'D'], ['4', '4', '4', '4', '4']], [1, 10, 10, 2], [3, 5, 5, 1])
Expected Output: 4
Explanation: Mode 1 reaches D in 4 moves, so time = 12. Mode 4 takes a longer path of 6 moves, but time = 6 because it is faster per block. Therefore mode 4 is chosen.
Hints
- For a fixed transportation mode, the problem becomes finding the shortest path on an unweighted grid with restricted cells.
- There are only 4 modes, so you can run a BFS for each mode independently, then compare total time and total cost.