Find shortest relationship path using BFS
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in graph representations and traversal algorithms—specifically BFS and adjacency-structure construction—for computing unweighted shortest paths and reasoning about reachability.
Constraints
- 0 <= len(relationships) <= 200000
- Each relationship contains exactly two node IDs
- Node IDs are hashable values such as strings or integers
- The graph may be disconnected
- Duplicate relationships and self-loops may appear
Examples
Input: ([['A', 'B'], ['B', 'C'], ['C', 'D']], 'A', 'D')
Expected Output: 3
Explanation: The shortest path is A -> B -> C -> D, which uses 3 edges.
Input: ([[1, 2], [2, 5], [1, 3], [3, 4], [4, 5]], 1, 5)
Expected Output: 2
Explanation: There are multiple paths, but the shortest is 1 -> 2 -> 5, which has 2 hops.
Input: ([['x', 'y'], ['a', 'b']], 'x', 'b')
Expected Output: -1
Explanation: The graph has two disconnected components, so b is unreachable from x.
Input: ([], 'solo', 'solo')
Expected Output: 0
Explanation: Start and target are the same, so the shortest path length is 0 even with no relationships.
Input: ([[1, 1], [1, 2], [1, 2], [2, 3]], 1, 3)
Expected Output: 2
Explanation: Self-loops and duplicate edges do not change the shortest path. The minimum path is 1 -> 2 -> 3.
Hints
- Since every relationship-hop has the same cost, BFS is the right traversal to find the shortest path.
- First build a dictionary that maps each node to its list of neighbors, then explore level by level from `start`.