← Pinterest Interview Insights
The instinct to BFS over stops instead of routes will burn you here.
Model the problem as a graph where each bus route is a node, and edges connect routes that share at least one stop. Then perform BFS from all routes containing the source stop to find the minimum number of buses to reach any route containing the target stop. If source and target are the same stop, return 0; if no path exists, return -1.
Pro tip: Clarify with the interviewer whether the source and target stops are guaranteed to be in the routes, and discuss trade-offs between building the route graph upfront versus on-the-fly to optimize for memory or time.
Ask about input size, whether source and target can be the same, and if stops are guaranteed to exist in the routes. This helps determine the optimal approach and avoid misunderstandings.
Treat each bus route as a node. Connect two routes with an edge if they share at least one stop. This transforms the problem into finding the shortest path in an unweighted graph.
Use a hash map to map each stop to the list of routes that contain it. Then, for each stop, connect all routes in its list to each other, avoiding duplicate edges.
Initialize a queue with all routes containing the source stop, marking them as visited with distance 1. BFS level by level until a route containing the target stop is found, returning the distance.
If source equals target, return 0. If BFS exhausts without reaching a target route, return -1. Otherwise, return the minimum number of buses (BFS distance).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.