FastPrepMinimum Bus Routes to a Destination

Minimum Bus Routes to a Destination

Pinterest logoPinterest● HardFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Each row in routes lists all stops served by one bus route. Boarding a route costs one bus; after boarding, you may travel to any stop on it. Return the minimum buses needed to travel from sourceStop to targetStop, or -1 if impossible.

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 7, then the second to 6.

Example 2

routes = [[1,5,7],[3,5]]sourceStop = 5targetStop = 5return = 0

The trip is already complete.

Example 3

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

The route groups are disconnected.

Constraints

  • 1 <= routes.length <= 500.
  • The total number of listed stops is at most 10^5.
  • Stops on one route are unique.

More Pinterest problems

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