815. Bus Routes
Asked at 16Amazon40Google33Bloomberg32Microsoft25Meta5.0Uber100Pinterest96Snap94DeltaX100PhonePe83BitGo77Info Edge72TikTok56Walmart Labs43Salesforce28Oracle27
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
assert Solution().numBusesToDestination([[1, 2, 7], [3, 6, 7]], 1, 6) == 2
assert Solution().numBusesToDestination([[7, 12], [4, 5, 15], [6], [15, 19], [9, 12, 13]], 15, 12) == -1
assert Solution().numBusesToDestination([[1, 2]], 1, 1) == 0
assert Solution().numBusesToDestination([[1, 2]], 3, 1) == -1
assert Solution().numBusesToDestination([[1, 7], [3, 5]], 5, 5) == 0
class Solution {
public int numBusesToDestination(int[][] routes, int source, int target) {
if (source == target) return 0;
Map<Integer, List<Integer>> at = new HashMap<>();
for (int i = 0; i < routes.length; i++) for (int s : routes[i]) at.computeIfAbsent(s, k -> new ArrayList<>()).add(i);
boolean[] used = new boolean[routes.length];
Set<Integer> seen = new HashSet<>(List.of(source));
Deque<Integer> q = new ArrayDeque<>(List.of(source));
for (int buses = 1; !q.isEmpty(); buses++) {
for (int i = q.size(); i > 0; i--) {
for (int r : at.getOrDefault(q.poll(), List.of())) {
if (used[r]) continue;
used[r] = true;
for (int s : routes[r]) {
if (s == target) return buses;
if (seen.add(s)) q.add(s);
}
}
}
}
return -1;
}
}
func numBusesToDestination(routes [][]int, source int, target int) int {
if source == target {
return 0
}
at := map[int][]int{} // stop -> routes through it
for i, route := range routes {
for _, s := range route {
at[s] = append(at[s], i)
}
}
used, seen, q := map[int]bool{}, map[int]bool{source: true}, []int{source}
for buses := 1; len(q) > 0; buses++ { // BFS over stops, one level per bus taken
next := []int{}
for _, stop := range q {
for _, r := range at[stop] {
if used[r] {
continue
}
used[r] = true
for _, s := range routes[r] {
if s == target {
return buses
}
if !seen[s] {
seen[s] = true
next = append(next, s)
}
}
}
}
q = next
}
return -1
}