Home
DSA Patterns
Breadth-First Search
Bus Routes
Bus Routes (LeetCode 815)
Bus Routes (LeetCode 815): find the fewest buses between two stops with a BFS whose levels count rides, not stops.
Examples
Bus 0 from stop 1 to stop 7, then bus 1 from stop 7 to stop 6.
The buses through stop 15 reach 4, 5 and 19 only: never one that serves 12.
Problem Understanding
routes[i] is the list of stops that bus i drives round, in a loop, for ever. You start at stop source, you want to reach stop target, and you may change buses at any stop two routes share (LeetCode 815).
- Input:
routes = [[1,2,7],[3,6,7]],source = 1,target = 6. - Output:
2: bus 0 from stop 1 to stop 7, change there, then bus 1 from stop 7 to stop 6. - Goal: the fewest buses, not the fewest stops. Riding one bus past twenty stops still costs 1.
When no chain of transfers reaches the target, return -1.
Algorithm Strategy
Fewest buses is a shortest-path question where every ride costs 1, so it is BFS. The difficulty is choosing what the nodes are.
Why not stop to stop. Joining every pair of stops on a route builds a clique: a route with 10^5 stops would need about 5 × 10^9 edges. The thing to walk is the route, not the pairs.
- Index the routes: one pass over every stop of every route builds
stop → the buses that serve it. - Queue stops, count buses: the queue holds stops, and each pass of the outer loop is one more bus taken, so every stop dequeued during that pass costs the same number of rides.
- Ride each bus once: for the stop at the front of the queue, look at the buses serving it. One already ridden is skipped, because everything it reaches is already known. A new one is marked ridden, and every stop on its route is examined.
- Stop at the target: the first ride that reaches the target ends the search, and the current count is the answer.
- Empty queue: no chain of transfers gets there, so return -1.
The two visited sets do different jobs. The bus set is what keeps the work linear: a route is walked at most once in the whole search. The stop set only keeps the queue from holding the same stop twice.
Interactive Visualization
LEFT = STOPS, RIGHT = BUSES · THE NUMBER ABOVE A STOP IS THE BUSES TAKEN TO REACH IT · GREEN RING = target
INDEX THE ROUTES
1 → 6
0 buses
stops reached
0
Answer
:
queue (front first)
Empty
buses ridden
None yet
Index the routes, stop by stop: 1: bus 0 · 2: bus 0 · 7: bus 0, bus 1 · 3: bus 1 · 6: bus 1
Next
Start at stop 1 with 0 buses taken
routes
source
Target
The ring on the left is the stops and the column on the right is the buses, with a line wherever a bus serves a stop, which is exactly the index the code builds in step 1. Riding a bus lights the line into it, then the line out to each stop on its route. The number above a stop is the value of buses when that stop joined the queue, so the moment the target lights up, the answer is already written above it.
Dry Run
Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6.
The index built first: 1 → bus 0, 2 → bus 0, 7 → bus 0 and bus 1, 3 → bus 1, 6 → bus 1.
buses |
Stop dequeued | Buses serving it | Ridden now | Stops on that route | Queue after |
|---|---|---|---|---|---|
| 1 | 1 | bus 0 | bus 0 | 1 is already known; 2 and 7 are new | [2, 7] |
| 2 | 2 | bus 0 | none: bus 0 has been ridden | - | [7] |
| 2 | 7 | bus 0, bus 1 | bus 1 (bus 0 skipped) | 3 is new, then 6 is the target | - |
Bus 1 reaches stop 6 while buses is 2, so the answer is 2. Stop 2 cost a dequeue and produced nothing, which is normal: the stop is reachable, but the only bus through it had already been ridden.
Edge Cases & Common Mistakes
Edge Cases:
source == target: return 0 before anything is built.- Unreachable target: the queue empties and the answer is -1.
- A target no route serves: the same -1, no ride can reach it.
- Size: up to 10^5 stops across all routes, which is why riding each route at most once matters.
Common Mistakes:
- Building a stop-to-stop graph, which is the clique that times out.
- Forgetting to mark a route as ridden, so its stops are walked again for every stop on it.
- Counting stops instead of buses: the counter goes up once per level, which is once per ride.
- Checking for the target only as a stop is dequeued, which costs an extra ride on the answer.
Solution Code
Index the stops once, then run a BFS over stops whose levels count bus rides (LeetCode 815).
Bus Routes Code
1var numBusesToDestination = function(routes, source, target) {2 if (source === target) {3 return 0;4 }5 const stopToBuses = new Map();6 for (let bus = 0; bus < routes.length; bus++) {7 for (const stop of routes[bus]) {8 if (!stopToBuses.has(stop)) {9 stopToBuses.set(stop, []);10 }11 stopToBuses.get(stop).push(bus);12 }13 }14 const queue = [source];15 let head = 0;16 const visitedStops = new Set([source]);17 const ridden = new Set();18 let buses = 0;19 while (head < queue.length) {20 buses++;21 const size = queue.length - head;22 for (let i = 0; i < size; i++) {23 const stop = queue[head++];24 for (const bus of stopToBuses.get(stop) || []) {25 if (ridden.has(bus)) {26 continue;27 }28 ridden.add(bus);29 for (const nextStop of routes[bus]) {30 if (nextStop === target) {31 return buses;32 }33 if (visitedStops.has(nextStop)) {34 continue;35 }36 visitedStops.add(nextStop);37 queue.push(nextStop);38 }39 }40 }41 }42 return -1;43};
Bus Routes in Python, Java, C++, TypeScript and C
Bus Routes in Python
from collections import deque
class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
if source == target:
return 0
stop_to_buses = {}
for bus, route in enumerate(routes):
for stop in route:
stop_to_buses.setdefault(stop, []).append(bus)
queue = deque([source])
visited_stops = {source}
ridden = set()
buses = 0
while queue:
buses += 1
for _ in range(len(queue)):
stop = queue.popleft()
for bus in stop_to_buses.get(stop, []):
if bus in ridden:
continue
ridden.add(bus)
for next_stop in routes[bus]:
if next_stop == target:
return buses
if next_stop in visited_stops:
continue
visited_stops.add(next_stop)
queue.append(next_stop)
return -1Bus Routes in Java
class Solution {
public int numBusesToDestination(int[][] routes, int source, int target) {
if (source == target) {
return 0;
}
Map<Integer, List<Integer>> stopToBuses = new HashMap<>();
for (int bus = 0; bus < routes.length; bus++) {
for (int stop : routes[bus]) {
stopToBuses.computeIfAbsent(stop, key -> new ArrayList<>()).add(bus);
}
}
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(source);
Set<Integer> visitedStops = new HashSet<>();
visitedStops.add(source);
boolean[] ridden = new boolean[routes.length];
int buses = 0;
while (!queue.isEmpty()) {
buses++;
int size = queue.size();
for (int i = 0; i < size; i++) {
int stop = queue.poll();
for (int bus : stopToBuses.getOrDefault(stop, new ArrayList<>())) {
if (ridden[bus]) {
continue;
}
ridden[bus] = true;
for (int nextStop : routes[bus]) {
if (nextStop == target) {
return buses;
}
if (visitedStops.contains(nextStop)) {
continue;
}
visitedStops.add(nextStop);
queue.offer(nextStop);
}
}
}
}
return -1;
}
}Bus Routes in C++
class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {
if (source == target) {
return 0;
}
unordered_map<int, vector<int>> stopToBuses;
for (int bus = 0; bus < (int)routes.size(); bus++) {
for (int stop : routes[bus]) {
stopToBuses[stop].push_back(bus);
}
}
queue<int> q;
q.push(source);
unordered_set<int> visitedStops;
visitedStops.insert(source);
vector<bool> ridden(routes.size(), false);
int buses = 0;
while (!q.empty()) {
buses++;
int size = q.size();
for (int i = 0; i < size; i++) {
int stop = q.front();
q.pop();
for (int bus : stopToBuses[stop]) {
if (ridden[bus]) {
continue;
}
ridden[bus] = true;
for (int nextStop : routes[bus]) {
if (nextStop == target) {
return buses;
}
if (visitedStops.count(nextStop)) {
continue;
}
visitedStops.insert(nextStop);
q.push(nextStop);
}
}
}
}
return -1;
}
};Bus Routes in TypeScript
function numBusesToDestination(routes: number[][], source: number, target: number): number {
if (source === target) {
return 0;
}
const stopToBuses = new Map<number, number[]>();
for (let bus = 0; bus < routes.length; bus++) {
for (const stop of routes[bus]) {
if (!stopToBuses.has(stop)) {
stopToBuses.set(stop, []);
}
stopToBuses.get(stop)!.push(bus);
}
}
const queue: number[] = [source];
let head = 0;
const visitedStops = new Set<number>([source]);
const ridden = new Set<number>();
let buses = 0;
while (head < queue.length) {
buses++;
const size = queue.length - head;
for (let i = 0; i < size; i++) {
const stop = queue[head++];
for (const bus of stopToBuses.get(stop) || []) {
if (ridden.has(bus)) {
continue;
}
ridden.add(bus);
for (const nextStop of routes[bus]) {
if (nextStop === target) {
return buses;
}
if (visitedStops.has(nextStop)) {
continue;
}
visitedStops.add(nextStop);
queue.push(nextStop);
}
}
}
}
return -1;
}Bus Routes in C
struct Pair {
int stop;
int bus;
};
static int byStop(const void* a, const void* b) {
const struct Pair* x = a;
const struct Pair* y = b;
if (x->stop != y->stop) {
return x->stop < y->stop ? -1 : 1;
}
return x->bus - y->bus;
}
/* The first index whose stop is >= key, so a stop's buses are one contiguous run. */
static int lowerBound(struct Pair* pairs, int size, int key) {
int lo = 0, hi = size;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (pairs[mid].stop < key) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
static int indexOf(int* stops, int size, int key) {
int lo = 0, hi = size - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (stops[mid] == key) {
return mid;
}
if (stops[mid] < key) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return -1;
}
static void freeAll(struct Pair* pairs, int* stops, char* visitedStop, char* ridden, int* queue) {
free(pairs);
free(stops);
free(visitedStop);
free(ridden);
free(queue);
}
int numBusesToDestination(int** routes, int routesSize, int* routesColSize, int source, int target) {
if (source == target) {
return 0;
}
int total = 0;
for (int bus = 0; bus < routesSize; bus++) {
total += routesColSize[bus];
}
struct Pair* pairs = malloc(total * sizeof(struct Pair));
int count = 0;
for (int bus = 0; bus < routesSize; bus++) {
for (int j = 0; j < routesColSize[bus]; j++) {
pairs[count].stop = routes[bus][j];
pairs[count].bus = bus;
count++;
}
}
qsort(pairs, total, sizeof(struct Pair), byStop);
int* stops = malloc((total + 1) * sizeof(int));
int stopCount = 0;
for (int k = 0; k < total; k++) {
if (stopCount == 0 || stops[stopCount - 1] != pairs[k].stop) {
stops[stopCount++] = pairs[k].stop;
}
}
char* visitedStop = calloc(stopCount + 1, sizeof(char));
char* ridden = calloc(routesSize, sizeof(char));
int* queue = malloc((total + 1) * sizeof(int));
int head = 0, tail = 0;
queue[tail++] = source;
int sourceIndex = indexOf(stops, stopCount, source);
if (sourceIndex >= 0) {
visitedStop[sourceIndex] = 1;
}
int buses = 0;
while (head < tail) {
buses++;
int size = tail - head;
for (int i = 0; i < size; i++) {
int stop = queue[head++];
for (int k = lowerBound(pairs, total, stop); k < total && pairs[k].stop == stop; k++) {
int bus = pairs[k].bus;
if (ridden[bus]) {
continue;
}
ridden[bus] = 1;
for (int j = 0; j < routesColSize[bus]; j++) {
int nextStop = routes[bus][j];
if (nextStop == target) {
freeAll(pairs, stops, visitedStop, ridden, queue);
return buses;
}
int index = indexOf(stops, stopCount, nextStop);
if (visitedStop[index]) {
continue;
}
visitedStop[index] = 1;
queue[tail++] = nextStop;
}
}
}
}
freeAll(pairs, stops, visitedStop, ridden, queue);
return -1;
}More practice: DSA interview questions with answers · patterns cheat sheet
