Bus Routes (LeetCode 815): Solution and Explanation

Hard
Array
Hash Table
Breadth First Search

Each bus loops forever along a fixed list of stops. Starting at a source stop, find the fewest buses you must ride to reach a target stop, or return -1 if the target cannot be reached.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

We want the fewest buses, not the fewest stops, which is the first thing to get right. Riding one bus from its first stop to its last costs one, no matter how many stops pass by. So a BFS where each step moves from one stop to the next stop on a route would measure the wrong thing.

A tempting fix is to build a graph of stops where two stops are connected if some bus serves both. That measures buses correctly, but a single route with 10^5 stops creates about 10^10 edges, which is hopeless. The better move is to make buses the nodes. Two buses are adjacent when they share a stop, and BFS over buses counts transfers directly: the starting buses are at distance 1, buses you can switch to from them are at distance 2, and so on.

To find neighboring buses without building that graph explicitly, precompute stop_to_buses, a map from each stop to the set of buses that pass through it. When BFS processes a bus, it scans that bus's stops. If one is the target, the current distance is the answer. Otherwise, for each stop not seen before, every bus through it that has not been visited joins the queue at distance plus one. Marking stops as visited is what keeps the work linear, because each stop's bus list is scanned only once across the whole search.

Approach: BFS over buses with a stop-to-buses map

  1. If source == target, return 0, since no bus is needed.
  2. Build stop_to_buses, mapping every stop to the set of bus indices that serve it.
  3. Seed the queue with every bus that stops at source, each at distance 1, and mark them visited. Mark source as a visited stop.
  4. Pop a bus and scan its stops. If a stop equals target, return the bus's distance.
  5. For each unvisited stop, mark it visited and enqueue every unvisited bus through it at distance plus one.
  6. If the queue empties, return -1.

Step-by-step example

routes = [[1, 2, 7], [3, 6, 7]], source = 1, target = 6
  1. stop_to_buses is {1: {0}, 2: {0}, 7: {0, 1}, 3: {1}, 6: {1}}.
  2. Stop 1 is served only by bus 0, so the queue starts as [(bus 0, 1)].
  3. Process bus 0: stop 1 is already visited. Stop 2 is new, but its only bus is 0, already visited. Stop 7 is new and is also served by bus 1, so enqueue (bus 1, 2).
  4. Process bus 1: stop 3 is not the target. Stop 6 is the target, so return 2.
  5. The answer is 2: ride bus 0 from stop 1 to stop 7, then bus 1 from 7 to 6.

Code: Python, Java, C++

1class Solution:
2    def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
3        if source == target:
4            return 0
5
6        # Map stop -> list of bus indices
7        stop_to_buses = defaultdict(set)
8        for i, route in enumerate(routes):
9            for stop in route:
10                stop_to_buses[stop].add(i)
11
12        # BFS on buses
13        queue = deque()
14        visited_buses = set()
15        visited_stops = {source}
16
17        for bus in stop_to_buses[source]:
18            queue.append((bus, 1))
19            visited_buses.add(bus)
20
21        while queue:
22            bus, dist = queue.popleft()
23            for stop in routes[bus]:
24                if stop == target:
25                    return dist
26                if stop not in visited_stops:
27                    visited_stops.add(stop)
28                    for next_bus in stop_to_buses[stop]:
29                        if next_bus not in visited_buses:
30                            visited_buses.add(next_bus)
31                            queue.append((next_bus, dist + 1))
32
33        return -1

Time and space complexity

Time

O(S)

S is the total number of stops across all routes. Building the map touches each entry once, each bus is dequeued once and its route scanned once, and each stop's bus list is scanned once because stops are marked visited.

Space

O(S)

The stop-to-buses map stores one entry per route stop, and the visited sets and queue are bounded by the number of stops and buses.

Other approaches

BFS over stops with route exhaustion (time O(S), space O(S))

BFS from the source stop where each level means one more bus. When you visit a stop, ride every unused bus through it to all of its stops, then mark that bus used so its route is never scanned again. The levels count buses, and the complexity is the same.

Explicit bus graph (time O(B² × L), space O(B²))

Build adjacency between every pair of buses that share a stop, often by intersecting sorted routes, then run BFS from the source buses to any bus that contains the target. It is easy to understand but building the graph can cost O(B² × L) for B buses.

Common mistakes

  • Forgetting the source == target case, which should return 0 even when the source is not on any route.
  • Counting stops traveled instead of buses boarded, which happens when BFS moves one stop at a time.
  • Marking buses visited but not stops, which makes the search rescan large bus lists for the same stop many times.
  • Building a stop graph with edges between all pairs of stops on a route, which explodes in memory for long routes.

Frequently asked questions

Why BFS over buses instead of stops?

The cost we minimize is the number of buses. Making buses the nodes means each BFS level is exactly one more bus, and it avoids connecting every pair of stops on a long route.

Why is BFS correct here rather than Dijkstra?

Every transfer costs exactly one bus, so all edges have equal weight. BFS finds shortest paths in unweighted graphs, so Dijkstra is unnecessary.

What is the time complexity of Bus Routes?

Linear in the total number of route entries. Each route is scanned when its bus is dequeued, and each stop's list of buses is scanned at most once thanks to the visited stop set.