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 - BFS Approach INPUT Bus Routes Network Bus 0 1 2 7 Bus 1 3 6 7 Transfer routes = [[1,2,7],[3,6,7]] source = 1, target = 6 SOURCE: 1 TARGET: 6 ALGORITHM STEPS 1 Build Stop-to-Bus Map Map each stop to buses 1-->[Bus0] 2-->[Bus0] 7-->[Bus0,1] 3,6-->[Bus1] 2 BFS from Source Queue buses at stop 1 Queue: [Bus0], Buses=1 3 Process Bus 0 Visit stops: 1, 2, 7 At stop 7: add Bus1 Queue: [Bus1], Buses=2 4 Process Bus 1 Visit stops: 3, 6, 7 Found target 6! Return 2 FINAL RESULT Optimal Path Found 1 START 7 TRANSFER 6 TARGET Bus 0 Bus 1 OUTPUT 2 Minimum buses needed 1 --[B0]--> 7 --[B1]--> 6 Key Insight: Treat buses as nodes (not stops) in BFS. Build a stop-to-bus mapping, then BFS explores buses reachable from current bus via shared stops. Each BFS level = one bus transfer. This reduces complexity from exploring all stops to exploring buses connected through transfer points. TutorialsPoint - Bus Routes | BFS Approach
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
89.3K 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