Bus Routes - Problem

You are given an array routes representing bus routes where routes[i] is a bus route that the i-th bus repeats forever.

For example, if routes[0] = [1, 5, 7], this means that the 0-th bus travels in the sequence 1 → 5 → 7 → 1 → 5 → 7 → 1 → ... forever.

You will start at the bus stop source (you are not on any bus initially), and you want to go to the bus stop target.

You can travel between bus stops by buses only. Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.

Input & Output

Example 1 — Basic Transfer
$ Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6
Output: 2
💡 Note: Take Bus 0 from stop 1 to stop 7, then transfer to Bus 1 from stop 7 to reach stop 6. Total: 2 buses.
Example 2 — Direct Route
$ Input: routes = [[7,12],[4,5,15],[6],[15,19,26,7]], source = 15, target = 12
Output: -1
💡 Note: No possible route from stop 15 to stop 12. Bus 1 contains 15, Bus 0 contains 12, but they don't share any common stops.
Example 3 — Same Stop
$ Input: routes = [[1,2,7],[3,6,7]], source = 6, target = 6
Output: 0
💡 Note: Already at target stop, no buses needed.

Constraints

  • 1 ≤ routes.length ≤ 500
  • 1 ≤ routes[i].length ≤ 105
  • All the values of routes[i] are unique
  • sum(routes[i].length) ≤ 105
  • 0 ≤ routes[i][j] < 106
  • 0 ≤ source, target < 106

Visualization

Tap to expand
Bus Routes: Find Minimum TransfersInput RoutesBus 0: [1, 2, 7]Bus 1: [3, 6, 7]Source: 1, Target: 6BFS ProcessStart: Bus 0 (has stop 1)Transfer at stop 7Reach: Bus 1 (has stop 6)OutputMinimum Buses: 2Bus 0 → Bus 1Path: 1 → 7 → 6Key Insight: Model as graph where buses are nodes, stops are connectionsBFS guarantees finding minimum number of bus transfers
Understanding the Visualization
1
Input
Bus routes and source/target stops
2
Process
Find minimum bus transfers using BFS
3
Output
Minimum number of buses needed
Key Takeaway
🎯 Key Insight: Think in terms of buses as graph nodes rather than individual stops - BFS on buses finds optimal transfer count
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
89.2K Views
Medium Frequency
~35 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen