Find the Best Commute Mode
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates competency in grid-based pathfinding, graph traversal, and multi-criteria optimization of path time and cost within the Coding & Algorithms domain.
Constraints
- 1 <= number of rows, number of columns <= 200
- All rows in grid have the same length
- grid contains exactly one 'S' and exactly one 'D'
- Each cell is one of 'S', 'D', 'X', '1', '2', '3', or '4'
- time and cost each contain exactly 4 positive integers
Examples
Input: (['S11','X1D','222'], [2,1,5,5], [3,4,1,1])
Expected Output: 1
Explanation: Mode 1 can reach D in 3 steps: S -> 1 -> 1 -> D. Its total time is 3*2 = 6 and total cost is 3*3 = 9. No other mode can reach the destination.
Input: (['SD'], [3,3,3,3], [5,2,4,2])
Expected Output: 2
Explanation: S and D are adjacent, so all modes can reach in 1 step. All total times are 3, so compare total cost. Modes 2 and 4 both have cost 2, and the smaller mode number is 2.
Input: (['SX','XD'], [1,1,1,1], [1,1,1,1])
Expected Output: -1
Explanation: From S, every orthogonally adjacent cell is blocked, so no mode can reach D.
Input: (['S3D','444'], [9,9,2,1], [9,9,5,2])
Expected Output: 4
Explanation: Mode 3 reaches D in 2 steps for total time 4 and total cost 10. Mode 4 reaches D in 4 steps for total time 4 and total cost 8. The total time ties, so mode 4 wins on lower total cost.
Input: (['S111D','1XXX1','11111'], [2,5,5,5], [7,1,1,1])
Expected Output: 1
Explanation: Only mode 1 can move through the grid. Its shortest path is the straight top row from S to D in 4 steps, so mode 1 is the answer.
Hints
- Treat each mode as a separate shortest-path problem. Since every move has equal step count, BFS gives the minimum number of steps for that mode.
- After finding the shortest step count for a mode, compare candidates using a tuple like (total_time, total_cost, mode_number).