Bus Routes
Bus Routes is a hard graphs problem solved with the bfs for shortest path pattern.
The best approach, optimal (bfs with a stop-to-buses map), runs in O(T) time and O(T) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (bfs over stops, rescanning every route) up.
Problem
A city runs several buses, each driving the same loop forever. routes[i] lists the stops that bus i visits, in order, and after the last stop it returns to the first.
You start at stop source (not on any bus yet) and want to reach stop target. You can board or leave a bus at any stop on its loop, and change buses wherever two loops share a stop. Moving between stops is only possible by bus.
Return the fewest buses you must ride to get from source to target, or -1 if it cannot be done.
Examples
Example 1
- Input
routes = [[2,5,8],[8,11,14],[14,20]], source = 2, target = 20- Output
3- Why
- Ride bus 0 from 2 to 8, change to bus 1 and ride to 14, then take bus 2 to 20.
Example 2
- Input
routes = [[1,4],[6,9]], source = 1, target = 9- Output
-1- Why
- The two buses share no stop, so there is no way to change from one to the other.
Example 3
- Input
routes = [[3,7,12],[12,15]], source = 7, target = 7- Output
0- Why
- You are already at the target, so no bus is needed.
Constraints
1 <= routes.length <= 5001 <= routes[i].length <= 10^5, and the stops within one route are distinct.- The total number of stops over all routes is at most
10^5. 0 <= routes[i][j], source, target < 10^6
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (BFS over stops, rescanning every route) | O(S · (R + T)) | O(T) |
| Optimal (BFS with a stop-to-buses map) | O(T) | O(T) |
1Brute force (BFS over stops, rescanning every route)
O(S · (R + T))Each of the S distinct stops checks all R routes and may rescan up to T total route entries.O(T)The per-route sets, the seen set and the queue.Run a BFS over stops where each level is one more bus ride. To expand a stop, check every route to see whether it serves that stop, and if it does, add all of its stops. Routes are not marked as used, so the same route can be scanned again from many stops.
- If source == target, return 0. Put each route's stops in a hash set.
- BFS from source; rides = 0. For each level, rides++.
- For each stop in the level and each route that contains it: for each stop s on that route, return rides if s == target, else enqueue s if unseen.
- If the queue empties, return -1.
class Solution {
public int numBusesToDestination(int[][] routes, int source, int target) {
if (source == target) return 0;
List<Set<Integer>> sets = new ArrayList<>();
for (int[] r : routes) {
Set<Integer> set = new HashSet<>();
for (int s : r) set.add(s);
sets.add(set);
}
Set<Integer> seen = new HashSet<>();
ArrayDeque<Integer> q = new ArrayDeque<>();
seen.add(source);
q.add(source);
int rides = 0;
while (!q.isEmpty()) {
rides++;
for (int size = q.size(); size > 0; size--) {
int stop = q.poll();
for (int b = 0; b < routes.length; b++) {
if (!sets.get(b).contains(stop)) continue;
for (int s : routes[b]) {
if (s == target) return rides;
if (seen.add(s)) q.add(s);
}
}
}
}
return -1;
}
}class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
if source == target:
return 0
sets = [set(r) for r in routes]
seen = {source}
q = deque([source])
rides = 0
while q:
rides += 1
for _ in range(len(q)):
stop = q.popleft()
for b in range(len(routes)):
if stop not in sets[b]:
continue
for s in routes[b]:
if s == target:
return rides
if s not in seen:
seen.add(s)
q.append(s)
return -1class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {
if (source == target) return 0;
vector<unordered_set<int>> sets;
for (auto& r : routes) sets.emplace_back(r.begin(), r.end());
unordered_set<int> seen = {source};
queue<int> q;
q.push(source);
int rides = 0;
while (!q.empty()) {
rides++;
for (int size = q.size(); size > 0; size--) {
int stop = q.front();
q.pop();
for (size_t b = 0; b < routes.size(); b++) {
if (!sets[b].count(stop)) continue;
for (int s : routes[b]) {
if (s == target) return rides;
if (seen.insert(s).second) q.push(s);
}
}
}
}
return -1;
}
};function numBusesToDestination(routes, source, target) {
if (source === target) return 0;
const sets = routes.map(r => new Set(r));
const seen = new Set([source]);
let level = [source], rides = 0;
while (level.length > 0) {
rides++;
const next = [];
for (const stop of level) {
for (let b = 0; b < routes.length; b++) {
if (!sets[b].has(stop)) continue;
for (const s of routes[b]) {
if (s === target) return rides;
if (!seen.has(s)) {
seen.add(s);
next.push(s);
}
}
}
}
level = next;
}
return -1;
}2Optimal (BFS with a stop-to-buses map)
O(T)T = total stops over all routes. Building the map and scanning each route once are both linear in T.O(T)The stop-to-buses map, the seen set and the queue.Precompute, for every stop, the list of buses that serve it. BFS over stops level by level, where each level is one more ride. When a stop is expanded, board each of its buses that has not been used yet, mark the bus used, and enqueue every stop on it. Since each bus is boarded at most once, every route list is scanned at most once.
- If source == target, return 0.
- busesAt[stop] = list of bus indices serving that stop.
- BFS from source with rides = 0; for each level, rides++.
- For each stop in the level and each unused bus b in busesAt[stop]: mark b used; for each stop s on route b, return rides if s == target, else enqueue s if unseen.
- Return -1 when the queue empties.
class Solution {
public int numBusesToDestination(int[][] routes, int source, int target) {
if (source == target) return 0;
Map<Integer, List<Integer>> busesAt = new HashMap<>();
for (int b = 0; b < routes.length; b++)
for (int s : routes[b]) busesAt.computeIfAbsent(s, k -> new ArrayList<>()).add(b);
boolean[] used = new boolean[routes.length];
Set<Integer> seen = new HashSet<>();
ArrayDeque<Integer> q = new ArrayDeque<>();
seen.add(source);
q.add(source);
int rides = 0;
while (!q.isEmpty()) {
rides++;
for (int size = q.size(); size > 0; size--) {
int stop = q.poll();
for (int b : busesAt.getOrDefault(stop, List.of())) {
if (used[b]) continue;
used[b] = true;
for (int s : routes[b]) {
if (s == target) return rides;
if (seen.add(s)) q.add(s);
}
}
}
}
return -1;
}
}class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
if source == target:
return 0
buses_at = defaultdict(list)
for b, route in enumerate(routes):
for s in route:
buses_at[s].append(b)
used = [False] * len(routes)
seen = {source}
q = deque([source])
rides = 0
while q:
rides += 1
for _ in range(len(q)):
stop = q.popleft()
for b in buses_at.get(stop, []):
if used[b]:
continue
used[b] = True
for s in routes[b]:
if s == target:
return rides
if s not in seen:
seen.add(s)
q.append(s)
return -1class Solution {
public:
int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {
if (source == target) return 0;
unordered_map<int, vector<int>> busesAt;
for (int b = 0; b < (int)routes.size(); b++)
for (int s : routes[b]) busesAt[s].push_back(b);
vector<bool> used(routes.size(), false);
unordered_set<int> seen = {source};
queue<int> q;
q.push(source);
int rides = 0;
while (!q.empty()) {
rides++;
for (int size = q.size(); size > 0; size--) {
int stop = q.front();
q.pop();
auto it = busesAt.find(stop);
if (it == busesAt.end()) continue;
for (int b : it->second) {
if (used[b]) continue;
used[b] = true;
for (int s : routes[b]) {
if (s == target) return rides;
if (seen.insert(s).second) q.push(s);
}
}
}
}
return -1;
}
};function numBusesToDestination(routes, source, target) {
if (source === target) return 0;
const busesAt = new Map();
routes.forEach((route, b) => {
for (const s of route) {
if (!busesAt.has(s)) busesAt.set(s, []);
busesAt.get(s).push(b);
}
});
const used = new Array(routes.length).fill(false);
const seen = new Set([source]);
let level = [source], rides = 0;
while (level.length > 0) {
rides++;
const next = [];
for (const stop of level) {
for (const b of busesAt.get(stop) || []) {
if (used[b]) continue;
used[b] = true;
for (const s of routes[b]) {
if (s === target) return rides;
if (!seen.has(s)) {
seen.add(s);
next.push(s);
}
}
}
}
level = next;
}
return -1;
}Edge cases to test
- source equals target (answer 0, even if no bus serves it)
- source or target is not on any route (answer -1)
- Source and target on the same bus (answer 1)
- A bus whose loop passes through many stops that are also served by other buses
Hints
Hint 1
The cost is the number of buses, not the number of stops. A single ride can cover any distance along its loop.
Hint 2
Breadth-first search counts the fewest steps. What should one BFS step be: one stop, or one bus?
Hint 3
Map each stop to the buses that serve it. When you board a bus, every stop on it becomes reachable with one more ride; mark the bus used so its stop list is never scanned twice.
FAQ
What is the best time complexity for Bus Routes?
Optimal (BFS with a stop-to-buses map) runs in O(T) time and O(T) extra space. T = total stops over all routes. Building the map and scanning each route once are both linear in T.
Which pattern does Bus Routes use?
It is a graphs problem that uses the bfs for shortest path pattern. Other problems with the same pattern: Shortest Path in Binary Matrix, Word Ladder, Minimum Knight Moves.
Is there a brute force solution for Bus Routes?
Yes. Brute force (BFS over stops, rescanning every route) takes O(S · (R + T)) time and O(T) space. Run a BFS over stops where each level is one more bus ride.
Which edge cases should I test for Bus Routes?
source equals target (answer 0, even if no bus serves it); source or target is not on any route (answer -1); Source and target on the same bus (answer 1); A bus whose loop passes through many stops that are also served by other buses.