Browse Curriculum
FAANGPrep Sprint
Hard
Bus Routes
Find the minimum number of buses to take to reach the destination.
25 min
Solve on LeetCodeProblem Understanding
You are given an array routes representing bus routes where routes[i] is a bus route that visits a sequence of stops in a loop.
- Input:
routes = [[1, 2, 7], [3, 6, 7]],source = 1,target = 6. - Goal: Travel from
sourcetotargetusing the least number of buses. - Rules: You can transfer between buses if they share a common stop.
Algorithm Strategy
This is a classic Shortest Path problem (Minimum number of edges/buses). This implies BFS.
Key Challenge:
If we treat Stops as nodes, a single route with 100 stops creates a 'clique' where every stop connects to every other stop. This leads to O(S^2) edges, which is too slow (TLE).
Optimized Graph:
Instead of Stop-to-Stop, think Bus-to-Bus or Stop-to-Bus.
- Preprocessing: Build a Graph where key=
Stopand value=List of Busesthat stop there. - BFS Traversal:
- Start at
sourcestop. - Find all
Busesat this stop. - Travel: For each bus, visit ALL its stops.
- Optimization: Keep a
visitedset for Buses (Routes) to ensure we don't ride the same bus twice (avoids the clique problem). - Also keep
visitedfor Stops to avoid checking the same stop redundantly.
- Start at
Interactive Visualization
Step 1 / 1
Visualization coming soon...
Initializing...
1x
Visualize buses as nodes in a graph. We hop from Bus to Bus via transfer stops.
ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
