FastPrepMinimum Bus Routes to a Destination

Minimum Bus Routes to a Destination

Google logoGoogle● HardNEW GRADONSITE INTERVIEW
Learn

Problem statement

Each row in routes lists the distinct stops served by one bus route. Boarding a route costs one bus; after boarding, you may travel to any stop on that route and transfer to another route serving the same stop.

Return the minimum number of buses needed to travel from sourceStop to targetStop. Return 0 when the two stops are equal and -1 when the destination is unreachable.

Function

minimumBusRoutes(routes: int[][], sourceStop: int, targetStop: int) → int

Examples

Example 1

routes = [[1,2,7],[3,6,7]]sourceStop = 1targetStop = 6return = 2

Take the first route to stop 7, then transfer to the second route and reach 6.

Example 2

routes = [[1,2,3],[4,5,6]]sourceStop = 1targetStop = 6return = -1

The two routes share no stop, so no transfer connects the endpoints.

Example 3

routes = [[5,8],[8,9]]sourceStop = 5targetStop = 5return = 0

No bus is needed when the source already equals the destination.

Constraints

  • 1 <= routes.length <= 500.
  • 1 <= routes[i].length <= 100000.
  • The total number of route-stop entries is at most 200000.
  • Stops within one route are distinct integers in [0,10^9].
  • 0 <= sourceStop,targetStop <= 10^9.

More Google problems

See Google hiring insights
public int minimumBusRoutes(int[][] routes, int sourceStop, int targetStop) {
    // Write your code here.
}
routes[[1,2,7],[3,6,7]]
sourceStop1
targetStop6
expected2
Checking account…