Each list in routes is a bus loop: bus i visits the stops in routes[i] and repeats them forever. You stand at stop source, not on any bus, and want to reach stop target. You can only move between stops by riding buses, and you may change buses at any stop they share.
Return the fewest buses you need to board to get there, or −1 if it cannot be done.
Example 1
Input: routes = [[5, 2, 8], [8, 6], [2, 7], [6, 3]],
source = 5, target = 3
Output: 3
Why: ride 5 → 8, then 8 → 6, then 6 → 32 more examples and the constraints
Example 2
Input: routes = [[3, 11], [6, 14, 20], [1], [20, 25],
[13, 11, 17]], source = 20, target = 11
Output: -1
Why: the buses through 20 never meet one through 11Example 3
Input: routes = [[4, 8]], source = 9, target = 9 Output: 0 Why: you are already at the target
Constraints
- 1 ≤ number of routes ≤ 500
- All routes together have at most 100,000 stops; no route repeats a stop
- 0 ≤ every stop number, source and target < 1,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- BFS over stopsO(Σ L²)
- BFS, each bus ridden onceO(Σ L)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for one route of 100,000 stops | Verdict |
|---|---|---|---|
| BFS over stops | O(Σ L²) | Too slow on long routes | |
| BFS, each bus once | O(Σ L) | Best; every route walked once |
L = length of one route; Σ L = all stops of all routes together.
Edge cases to test
- Source equals target. Return 0, even if no bus stops there.
- Source on no route. No bus can be boarded: return −1.
- Target unreachable. The queue empties without seeing it: return −1.
- A shortcut bus. One bus covering both ends beats a chain of short hops; BFS finds it at level 1.
- One very long route. Marking buses used keeps it to one scan.
Common mistakes
- Counting stops travelled instead of buses boarded.
- Not marking buses as used, so long routes are rescanned from every stop.
- Returning −1 when source equals target but sits on no route; the answer is 0.
How to talk through it
- 1Clarify. Does riding along a route cost anything? What if source equals target?
- 2Model it. Fewest boardings is a shortest path where one bus is one edge level: BFS.
- 3Give the first BFS. Pop stops and ride every bus through them; point out the repeated route scans.
- 4Fix it. Mark each bus when first ridden; now every route is walked once.
- 5Test out loud. Run source = target, an unreachable target and a shortcut bus.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?