695. Fewest Buses

A city has routes.length bus lines. The line routes[i] lists the stops it serves and runs in an endless loop, so you may board it at any of its stops and ride to any other stop of the same line. Different lines may share stops. Stop ids are integers, and the stops inside one line are distinct.

You are at stop source and want to reach stop target, travelling only by bus (no walking between stops). Return the smallest number of lines you have to board, or -1 if the trip is impossible. If source == target the answer is 0. Build a map from each stop to the lines that serve it, so that every line is boarded at most once during the search.

Example 1

Input:
routes = [[2,5,9],[9,14],[14,3,8]]source = 2target = 8
Output:
3
Explanation:

Board line 0 at stop 2 and ride to stop 9, switch to line 1 to reach stop 14, switch to line 2 and get off at stop 8: 3 lines.

Example 2

Input:
routes = [[1,2],[3,4]], source = 1, target = 4
Output:
-1
Explanation:

The two lines share no stop, so stop 4 cannot be reached from stop 1.

Example 3

Input:
routes = [[10,20],[20,30,40],[40,50],[10,50]]source = 10target = 50
Output:
1
Explanation:

Line 3 serves both stop 10 and stop 50, so a single ride is enough even though a longer chain of lines also exists.

Constraints

1 ≤ routes.length ≤ 300

1 ≤ routes[i].length and the total number of stops over all lines is at most 30000

0 ≤ routes[i][j] ≤ 99999, and the stops within one line are distinct

0 ≤ source, target ≤ 99999

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms

Expected complexity

Time
O(total stops)
Space
O(total stops)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…