The Shortest Distance After Road Addition Queries I interview question gives you n cities numbered 0 to n-1, initially connected in a chain (0→1→2→...→n-1). You receive a series of road-addition queries, each adding a directed shortcut edge (u, v). After each query, compute the shortest path from city 0 to city n-1 using BFS (since all edges have unit weight). Return an array of shortest distances, one per query.
Microsoft and Google ask this problem because it tests incremental graph construction with BFS re-evaluation — a pattern common in dynamic network analysis, routing algorithm updates, and transportation planning. It evaluates whether candidates can efficiently maintain and re-query a shortest path after structural changes, and whether they understand that BFS (not Dijkstra) is optimal for unweighted graphs.
The pattern is incremental BFS after each graph modification. Maintain an adjacency list initialized with the chain edges (i → i+1 for all i). For each query (u, v), add the edge u → v to the adjacency list. Then run BFS from node 0 to find the shortest path to node n-1. Append the BFS result to the answer array. Since each BFS is O(n + m) and there are q queries, total time is O(q × (n + m)).
n = 5. Initial edges: 0→1, 1→2, 2→3, 3→4. Initial shortest path: 4.
Query [2,4]: add edge 2→4. BFS from 0: 0→1→2→4. Distance = 3. Query [0,2]: add edge 0→2. BFS from 0: 0→2→4. Distance = 2.
Result: [3, 2].
For the Shortest Distance After Road Addition Queries I coding problem, the BFS graph interview pattern with incremental graph updates is the approach. The simplest implementation: use an adjacency list, add one edge per query, and re-run BFS. Microsoft and Google interviewers may ask about optimization for Part II (many queries) — know that for large query sets, more advanced techniques like LCT (link-cut trees) or Dijkstra with priority queues can improve performance. For this variant, clean BFS implementation is sufficient and expected.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| The Time When the Network Becomes Idle | Medium | Solve | |
| Maximum Candies You Can Get from Boxes | Hard | Solve | |
| Minimum Operations to Convert Number | Medium | Solve | |
| Shortest Path with Alternating Colors | Medium | Solve | |
| Shortest Cycle in a Graph | Hard | Solve |