← Uber Interview InsightsMachine Learning Engineer
My first instinct was plain BFS on stops, which is wrong because the search space explodes.
Model the problem as a graph where each bus route is a node, and edges exist between 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 upfront that if the source and target stops are identical, the answer is 0, and if either stop is not in any route, return -1. This shows attention to edge cases and prevents miscommunication.
Confirm that buses loop forever, so you can board any bus at any stop it serves. Discuss edge cases: source equals target (return 0), source or target not in any route (return -1), and multiple routes containing the same stop.
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, where each edge represents taking one additional bus.
Use a hash map to map each stop to the list of routes that include it. Then, for each stop, connect all routes that share that stop. This avoids O(R^2 * S) comparisons and achieves O(total stops across routes) time.
Initialize a queue with all routes containing the source stop (each counts as 1 bus). Perform BFS, tracking visited routes. When you encounter a route containing the target stop, return the current bus count. If the queue empties without reaching the target, return -1.
State that time complexity is O(N) where N is total number of stops across all routes, and space is O(N) for the graph and visited set. Mention that bidirectional BFS or early termination can optimize further.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.