Implement BFS to Find Shortest Path in Graph
Company: Amazon
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates understanding of graph traversal algorithms, particularly breadth-first search, and competency in computing shortest paths and reconstructing an example shortest route in large undirected graphs.
Constraints
- 1 <= n <= 200000
- 0 <= len(edges) <= 400000
- 0 <= u, v < n for every edge [u, v]
- 0 <= source, target < n
- Graph is undirected and may be disconnected
- Implement iterative BFS using a queue (no recursion)
- Return one shortest path; if none exists, return distance -1 and empty path
Hints
- Use a queue and a visited structure to explore nodes level by level.
- Track each node's predecessor to reconstruct the path once the target is found.
- You can stop the BFS as soon as the target is discovered; distance is path length minus one.