Grokking Graph Algorithms for Coding Interviews
Vote

0% completed

Solution: Bus Routes

Problem Statement

You are given an array routes where routes[i] is the list of bus stops that the i<sup>the</sup> bus travels in a cyclic manner. For example, if routes[0] = [2, 3, 7], it means that bus 0 travels through the stops 2 -> 3 -> 7 -> 2 -> 3 -> 7 ... and then repeats this sequence indefinitely.

You start at a bus stop called source and wish to travel to a bus stop called target using the bus routes. You can switch buses at any bus stop that is common to the routes of two buses.

Return the minimum number of buses you need to take to travel from source to

.....

.....

.....

Like the course? Get enrolled and start learning!
Nivetha Govindan

Nivetha Govindan

· a year ago

int[][] routesA = {{1,2,7}, {3, 6, 7}}; System.out.println(solution.numBusesToDestination(routesA, 8, 6)); // Output: 3 // We need a null check, before getting list of buses, code fails for below test case
Christopher Kwong

Christopher Kwong

· 5 months ago

shouldnt the time complexity in this solution be O(MxK) since visited_stops and visited_buses will ensure that all buses and all stops are only visited once