Implement BFS shortest paths with reconstruction
Company: MathWorks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Take-home Project
Quick Answer: This question evaluates understanding of graph traversal via breadth-first search, computation of shortest paths in unweighted graphs, and path reconstruction using parent arrays, assessing algorithmic reasoning and implementation skills in the Coding & Algorithms domain.
Constraints
- 1 <= n <= 10^5
- 0 <= s < n
- 0 <= m <= 2 * 10^5 (m = total number of directed entries across the adjacency list)
- Each entry in adj[u] is a valid vertex index in [0, n-1]
- The graph is unweighted and may be disconnected
Examples
Input: (6, [[1, 2], [0, 3], [0, 3, 4], [1, 2, 5], [2, 5], [3, 4]], 0)
Expected Output: [[0, 1, 1, 2, 2, 3], [-1, 0, 0, 1, 2, 3]]
Explanation: Connected graph from source 0. Distances grow level by level; parent records the discoverer of each vertex, e.g. parent[5]=3 (path 0->1->3->5).
Input: (5, [[1], [0, 2], [1], [4], [3]], 0)
Expected Output: [[0, 1, 2, -1, -1], [-1, 0, 1, -1, -1]]
Explanation: Disconnected graph: component {0,1,2} is reachable from source 0; component {3,4} is not, so vertices 3 and 4 keep dist=-1 and parent=-1.
Input: (1, [[]], 0)
Expected Output: [[0], [-1]]
Explanation: Single isolated vertex which is the source: dist[0]=0, parent[0]=-1.
Input: (4, [[], [], [], []], 2)
Expected Output: [[-1, -1, 0, -1], [-1, -1, -1, -1]]
Explanation: No edges and source 2: only vertex 2 is reachable (distance 0); all other vertices remain unreachable.
Input: (3, [[1, 2], [0, 2], [0, 1]], 1)
Expected Output: [[1, 0, 1], [1, -1, 1]]
Explanation: Triangle with source 1: vertices 0 and 2 are both one edge away and are discovered directly from 1, so parent[0]=parent[2]=1.
Hints
- BFS visits vertices in non-decreasing order of distance from the source, so the first time you reach a vertex is along a shortest path.
- Use a single dist array initialized to -1 as both the 'visited' marker and the distance: dist[v] == -1 means v is unvisited/unreachable.
- When you pop u and look at a neighbor v that is still unvisited, set dist[v] = dist[u] + 1 and parent[v] = u, then enqueue v.
- Process adj[u] in order and only set parent[v] on first discovery so the reconstructed path is deterministic. parent[s] stays -1, and any vertex never reached keeps dist = parent = -1.