SDE & MLE Prep

815. Bus Routes

Problem

routes[i] lists the stops of bus i, which loops through them forever. Starting at stop source (not on any bus), return the fewest buses you must ride to reach stop target, or −1 if you can't.

Example: routes = [[1,2,7],[3,6,7]], source = 1, target = 6 → 2

Constraints: up to 500 routes and 10⁵ stops per route.

BFS where one "step" is riding one bus: from the current stops, board every not-yet-used route through them and reach all of that route's stops. Index stop → routes first; mark routes as used so each route is expanded once.

routes: 0:[1 2 7]  1:[3 6 7]      source 1, target 6
bus 1: stop 1 -> route 0 -> stops {2, 7}
bus 2: stop 7 -> route 1 -> stops {3, 6}  -> target reached, answer 2

Complexity: O(Σ route lengths).

class Solution:
    def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
        if source == target:
            return 0
        at = defaultdict(list)                        # stop -> routes through it
        for i, route in enumerate(routes):
            for s in route:
                at[s].append(i)
        used, seen, q, buses = set(), {source}, deque([source]), 0
        while q:
            buses += 1
            for _ in range(len(q)):
                for r in at[q.popleft()]:
                    if r in used:
                        continue
                    used.add(r)
                    for s in routes[r]:
                        if s == target:
                            return buses
                        if s not in seen:
                            seen.add(s)
                            q.append(s)
        return -1