Classic BFS and I knew it immediately, which honestly made me a little sloppy at first.
Model the problem as an unweighted graph and use BFS from the source to find the shortest path to the target, as BFS guarantees the minimum number of edges. Handle edge cases upfront (same person, disconnected graph) and maintain a parent map to reconstruct the path if needed.
Pro tip: Mention that BFS is optimal for unweighted graphs and that bidirectional BFS can significantly reduce search space in large graphs. Also, clarify with the interviewer whether the graph is connected and if the path reconstruction is required, as this affects the implementation.
Confirm if the graph is undirected, if nodes are 0-indexed or 1-indexed, and whether path reconstruction is needed. Handle trivial cases: if source == target, return 0; if either node is not in the graph, return -1.
Explain that BFS is ideal for finding shortest paths in unweighted graphs because it explores nodes in order of distance from the source. Mention that DFS would not guarantee the shortest path.
Use a queue to traverse the graph level by level, keeping track of visited nodes and their distances from the source. Stop when the target is found and return the distance.
Maintain a parent map during BFS to record the predecessor of each visited node. Once the target is reached, backtrack from target to source using the parent map to build the shortest path.
State that time complexity is O(V + E) and space is O(V). For very large graphs, discuss bidirectional BFS to reduce time and space, and mention adjacency list representation for efficiency.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.