Implement Random Connectivity and Grid Routing
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of randomized combinatorial sampling and graph connectivity by requiring a uniformly random minimal set of inter-group edges that connects disjoint components, and it probes reasoning about sampling distributions and biases that can arise from naïve randomized or MST-style approaches; category/domain: Coding & Algorithms, graph theory and randomized algorithms, level: conceptual understanding with practical algorithm design considerations. The grid routing problem evaluates shortest-path and multi-criteria optimization skills—finding time-minimal routes with cost tie-breaking, mode-switch penalties, and switch-count constraints—testing the ability to model augmented state spaces and perform constrained search; category/domain: Coding & Algorithms, graph algorithms and dynamic programming, level: practical algorithm implementation and optimization.
Constraints
- 1 <= rows, cols <= 100
- grid contains exactly one 'S' and exactly one 'D'
- Each grid cell is one of 'S', 'D', 'X', '1', '2', '3', '4'
- len(cost) == 4 and len(time) == 4
- 1 <= cost[i], time[i] <= 10^6
- 0 <= switch_penalty <= 10^6
- 0 <= max_switches <= 20
Examples
Input: (["S11", "XX1", "11D"], [5, 7, 9, 11], [2, 3, 4, 5], 4, 0)
Expected Output: (8, 20)
Explanation: The only valid route uses mode 1 for 4 steps: S -> 1 -> 1 -> 1 -> D. Total time is 4*2 = 8 and total cost is 4*5 = 20.
Input: (["S1D", "222"], [5, 1, 8, 8], [2, 1, 4, 4], 3, 0)
Expected Output: (4, 4)
Explanation: Top route uses mode 1 for 2 steps: time 4, cost 10. Bottom route uses mode 2 for 4 steps: time 4, cost 4. Same time, so choose lower cost.
Input: (["S12D", "1111"], [1, 10, 7, 7], [5, 1, 3, 3], 1, 1)
Expected Output: (8, 21)
Explanation: The fast route is S -> 1 -> 2 -> D. Its time is 5 + (1 switch penalty + 1) + 1 = 8 and its cost is 1 + 10 + 10 = 21. Any all-mode-1 detour is slower.
Input: (["S12D", "1111"], [1, 10, 7, 7], [5, 1, 3, 3], 1, 0)
Expected Output: (25, 5)
Explanation: With zero switches, the route through cell '2' is not allowed after entering mode 1. The best valid path stays on mode 1 for 5 steps, giving time 25 and cost 5.
Input: (["SXD"], [1, 1, 1, 1], [1, 1, 1, 1], 2, 3)
Expected Output: (-1, -1)
Explanation: The obstacle blocks the only possible path, so the destination cannot be reached.
Input: (["SD"], [3, 5, 2, 4], [5, 5, 1, 1], 100, 0)
Expected Output: (1, 2)
Explanation: S and D are adjacent, so you may move directly in one step using any single mode. Modes 3 and 4 both take time 1, and mode 3 is cheaper.
Hints
- A plain BFS is not enough because steps have different time and cost values. Think about shortest paths on a weighted graph.
- Your state needs more than just (row, col). The best route can depend on the current mode and how many switches you have already used.