KatInterview

833. Bus Routes

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum number of buses required to travel from a source bus stop to a target bus stop. The bus routes are given, and we can switch buses at any stop where their routes intersect.

Solution

Bus Routes in Python

import collections

class Solution:
    def numBusesToDestination(self, routes: list[list[int]], source: int, target: int) -> int:
        # Base case: source and target are the same.
        if source == target:
            return 0

        # 1. Preprocessing: Map each stop to a list of routes that pass through it.
        stop_to_routes = collections.defaultdict(list)
        for i, route in enumerate(routes):
            for stop in route:
                stop_to_routes[stop].append(i)

        # Early exit if source stop is not on any route.
        if source not in stop_to_routes:
            return -1

        # 2. BFS Setup
        q = collections.deque()  # Queue of route indices
        visited_routes = set()

        # 3. BFS Initialization: Start with routes that contain the source stop.
        for route_idx in stop_to_routes[source]:
            q.append(route_idx)
            visited_routes.add(route_idx)

        buses_taken = 1

        # 4. BFS Traversal
        while q:
            level_size = len(q)
            for _ in range(level_size):
                current_route_idx = q.popleft()

                # Iterate through stops of the current route.
                for stop in routes[current_route_idx]:
                    # Check if we've reached the target.
                    if stop == target:
                        return buses_taken
                    
                    # Find next routes from the current stop.
                    for next_route_idx in stop_to_routes[stop]:
                        if next_route_idx not in visited_routes:
                            visited_routes.add(next_route_idx)
                            q.append(next_route_idx)
            
            buses_taken += 1

        # 5. Target not reachable.
        return -1

Bus Routes in Java

class Solution {
    public int numBusesToDestination(int[][] routes, int source, int target) {
        // Base case: source and target are the same.
        if (source == target) {
            return 0;
        }

        // 1. Preprocessing: Map each stop to a list of routes that pass through it.
        Map<Integer, List<Integer>> stopToRoutes = new HashMap<>();
        for (int i = 0; i < routes.length; i++) {
            for (int stop : routes[i]) {
                stopToRoutes.computeIfAbsent(stop, k -> new ArrayList<>()).add(i);
            }
        }

        // Early exit if source stop is not on any route.
        if (!stopToRoutes.containsKey(source)) {
            return -1;
        }

        // 2. BFS Setup
        Queue<Integer> q = new ArrayDeque<>(); // Queue of route indices
        boolean[] visitedRoutes = new boolean[routes.length];

        // 3. BFS Initialization: Start with routes that contain the source stop.
        for (int routeIdx : stopToRoutes.get(source)) {
            q.offer(routeIdx);
            visitedRoutes[routeIdx] = true;
        }

        int busesTaken = 1;

        // 4. BFS Traversal
        while (!q.isEmpty()) {
            int levelSize = q.size();
            for (int i = 0; i < levelSize; i++) {
                int currentRouteIdx = q.poll();

                // Iterate through stops of the current route.
                for (int stop : routes[currentRouteIdx]) {
                    // Check if we've reached the target.
                    if (stop == target) {
                        return busesTaken;
                    }

                    // Find next routes from the current stop.
                    // Using getOrDefault because a stop might have been removed in an optimized version.
                    List<Integer> nextRoutes = stopToRoutes.get(stop);
                    if (nextRoutes == null) continue;

                    for (int nextRouteIdx : nextRoutes) {
                        if (!visitedRoutes[nextRouteIdx]) {
                            visitedRoutes[nextRouteIdx] = true;
                            q.offer(nextRouteIdx);
                        }
                    }
                }
            }
            busesTaken++;
        }

        // 5. Target not reachable.
        return -1;
    }
}

Bus Routes in C++

class Solution {
public:
    int numBusesToDestination(vector<vector<int>>& routes, int source, int target) {
        if (source == target) {
            return 0;
        }

        // 1. Preprocessing: Map each stop to a list of routes that pass through it.
        unordered_map<int, vector<int>> stopToRoutes;
        for (int i = 0; i < routes.size(); ++i) {
            for (int stop : routes[i]) {
                stopToRoutes[stop].push_back(i);
            }
        }

        // Early exit if source stop is not on any route.
        if (stopToRoutes.find(source) == stopToRoutes.end()) {
            return -1;
        }

        // 2. BFS Setup
        queue<int> q; // Queue of route indices
        vector<bool> visitedRoutes(routes.size(), false);

        // 3. BFS Initialization: Start with routes that contain the source stop.
        for (int routeIdx : stopToRoutes[source]) {
            q.push(routeIdx);
            visitedRoutes[routeIdx] = true;
        }

        int busesTaken = 1;

        // 4. BFS Traversal
        while (!q.empty()) {
            int levelSize = q.size();
            for (int i = 0; i < levelSize; ++i) {
                int currentRouteIdx = q.front();
                q.pop();

                // Iterate through stops of the current route.
                for (int stop : routes[currentRouteIdx]) {
                    // Check if we've reached the target.
                    if (stop == target) {
                        return busesTaken;
                    }

                    // Find next routes from the current stop.
                    // stopToRoutes[stop] has all routes passing through this stop.
                    for (int nextRouteIdx : stopToRoutes[stop]) {
                        if (!visitedRoutes[nextRouteIdx]) {
                            visitedRoutes[nextRouteIdx] = true;
                            q.push(nextRouteIdx);
                        }
                    }
                }
            }
            busesTaken++;
        }

        // 5. Target not reachable.
        return -1;
    }
};

Bus Routes in TypeScript

function numBusesToDestination(routes: number[][], source: number, target: number): number {
    // Base case: source and target are the same.
    if (source === target) {
        return 0;
    }

    // 1. Preprocessing: Map each stop to a list of routes that pass through it.
    const stopToRoutes = new Map<number, number[]>();
    for (let i = 0; i < routes.length; i++) {
        for (const stop of routes[i]) {
            if (!stopToRoutes.has(stop)) {
                stopToRoutes.set(stop, []);
            }
            stopToRoutes.get(stop)!.push(i);
        }
    }

    // Early exit if source stop is not on any route.
    if (!stopToRoutes.has(source)) {
        return -1;
    }

    // 2. BFS Setup
    const q: number[] = []; // Using an array as a queue for route indices
    const visitedRoutes = new Set<number>();

    // 3. BFS Initialization: Start with routes that contain the source stop.
    for (const routeIdx of stopToRoutes.get(source)!) {
        q.push(routeIdx);
        visitedRoutes.add(routeIdx);
    }

    let busesTaken = 1;

    // 4. BFS Traversal
    while (q.length > 0) {
        const levelSize = q.length;
        for (let i = 0; i < levelSize; i++) {
            const currentRouteIdx = q.shift()!; // Dequeue

            // Iterate through stops of the current route.
            for (const stop of routes[currentRouteIdx]) {
                // Check if we've reached the target.
                if (stop === target) {
                    return busesTaken;
                }

                // Find next routes from the current stop.
                const nextRoutes = stopToRoutes.get(stop);
                if (nextRoutes) {
                    for (const nextRouteIdx of nextRoutes) {
                        if (!visitedRoutes.has(nextRouteIdx)) {
                            visitedRoutes.add(nextRouteIdx);
                            q.push(nextRouteIdx); // Enqueue
                        }
                    }
                }
            }
        }
        busesTaken++;
    }

    // 5. Target not reachable.
    return -1;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.