Bus Routes

50 min · numBusesToDestination()

The shortest trip isn't about how many stops the bus passes. It's about how many times you have to board a bus.

routes[i] lists every stop visited by bus route i; that bus keeps cycling through its listed stops. You begin at stop source without being on a bus. Return the fewest buses you must take to reach stop target.

You may board any route containing your current stop, ride to any other stop on that route, then transfer to another route containing that stop.

Ground rules:

  • Return 0 when source == target — you don't need to board anything.
  • Return -1 when no chain of routes connects the two stops.
  • Count buses boarded, not stops visited or transfers made.

Constraints

  • 1 <= routes.length <= 500
  • 1 <= routes[i].length
  • The total number of stop entries across all routes is at most 100_000.
  • 0 <= routes[i][j], source, target <= 1_000_000
  • Stops within one route are unique.

Hints

Choose the right state

Riding from one stop to another on the same route costs no extra bus. Boarding a new route is the action that increases the answer, so consider searching routes rather than individual stops.

Build the transfer board

Create an index from each stop to the route numbers that visit it. That turns "which buses can I transfer to here?" into a direct lookup.

One layer, one more bus

Seed the search with every route serving source, each at cost 1. A neighboring route shares at least one stop, and entering it adds exactly one bus.

Follow-up

If each route charged a different fare, how would you change the search to minimize total cost instead of buses boarded?

Visible cases

Examples

Example 1

ready
Input
routes = [
  [
    1,
    2,
    7
  ],
  [
    3,
    6,
    7
  ]
]
source = 1
target = 6
Expected
2
Why
take the route serving 1 and 7, then transfer at 7 to the route serving 6

Example 2

ready
Input
routes = [
  [
    4,
    5
  ],
  [
    8,
    9
  ]
]
source = 4
target = 4
Expected
0
Why
source and target are the same stop, so no bus is needed

Example 3

ready
Input
routes = [
  [
    1,
    2,
    3
  ],
  [
    7,
    8,
    9
  ]
]
source = 1
target = 9
Expected
-1
Why
the two route components share no transfer stop

Interview signal

Asked at

AmazonGoogleUber
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite