The key thing nobody tells you upfront: BFS over routes, not stops.
Model the problem as a graph where each bus route is a node, and edges exist between routes that share a stop. Use BFS from all routes containing the source stop to find the minimum number of routes (buses) to reach any route containing the target stop. Handle edge cases like source equals target (0 buses) and unreachable target (-1).
Pro tip: Clarify that you're counting buses (routes), not stops, and that you can transfer at any common stop. Mention that BFS is optimal because each bus ride adds uniform cost, and precomputing stop-to-routes mapping avoids redundant checks.
Confirm that each bus route is a node, and two routes are connected if they share at least one stop. The goal is to find the shortest path in terms of number of routes from any route containing the source to any route containing the target.
Create a hash map from each stop to the list of routes that include it. This allows efficient lookup of which routes serve a given stop.
Find all routes that contain the source stop and enqueue them with distance 1 (since taking one bus). If the source stop is the target, return 0 immediately.
While the queue is not empty, pop a route, and for each stop on that route, find all other routes serving that stop. If a route hasn't been visited, mark it visited and enqueue with distance+1. If any of these routes contains the target stop, return the distance.
If BFS completes without reaching a route containing the target, return -1. Otherwise, the first time we encounter a route with the target, return the current distance.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.