FastPrepFewest Buses with the Full Route

Fewest Buses with the Full Route

Microsoft logoMicrosoft● HardNEW GRADONSITE INTERVIEW

Problem statement

You are given two stops, source and destination, and a list routes. Each routes[i] lists all the stops one bus route passes. A bus connects any two stops on its route, in either direction. Two routes that pass the same stop let you transfer there. Each route you ride counts as one bus.

Find the fewest buses from source to destination, and return the full plan as a list of rows:

  • The first row holds one number: the fewest buses. It is 0 when source equals destination, and -1 when destination cannot be reached.
  • When you ride at least one bus, one more row follows for each bus, in riding order: [route, boardStop, getOffStop], where route is the index in routes. The first boardStop is source, the last getOffStop is destination, and each other getOffStop is where you transfer.

Several plans may use the fewest buses. Return the one chosen by these rules:

  • Compare the plans' lists of route indexes from left to right, and take the smallest list.
  • Between two routes in a row, transfer at the smallest stop they share.

Function

fewestBusesWithRoute(source: int, destination: int, routes: int[][]) → int[][]

Examples

Example 1

source = 10destination = 70routes = [[10,20,30],[25,30,40,50],[50,60,70],[20,80]]return = [[3],[0,10,30],[1,30,50],[2,50,70]]

Stop 10 is only on route 0, and stop 70 is only on route 2. Those two routes share no stop, so at least three buses are needed.

Ride route 0 from 10 to 30, the only stop it shares with route 1. Ride route 1 from 30 to 50, the only stop it shares with route 2. Ride route 2 from 50 to 70. Route 3 is not needed.

Example 2

source = 10destination = 70routes = [[10,20,30],[40,50],[60,70]]return = [[-1]]

Stop 10 is only on route 0, stop 70 is only on route 2, and no two routes share a stop. The destination cannot be reached, so the only row is [-1].

Example 3

source = 1destination = 9routes = [[1,4,2],[1,3],[9,4,2],[3,9]]return = [[2],[0,1,2],[2,2,9]]

No single route has both 1 and 9. Two plans use two buses: routes [0, 2] and routes [1, 3]. The list [0, 2] is smaller.

Routes 0 and 2 share stops 4 and 2, so the transfer is at the smaller stop, 2. Ride route 0 from 1 to 2, then route 2 from 2 to 9.

Constraints

  • 1 <= routes.length <= 500
  • 1 <= routes[i].length <= 5000
  • The total number of stops across all routes is at most 5000.
  • 0 <= routes[i][j] <= 10^6
  • 0 <= source <= 10^6
  • 0 <= destination <= 10^6
  • All stops in one route are different.

More Microsoft problems

See Microsoft hiring insights
Saved
public int[][] fewestBusesWithRoute(int source, int destination, int[][] routes) {
    // Write your code here.
}
Checking account…