Python 0815.py
class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
if source == target:
return 0
stop2bus = defaultdict(set)
for bus, stops in enumerate(routes):
for s in stops:
stop2bus[s].add(bus)
if source not in stop2bus:
return -1
if target not in stop2bus:
return -1
todo = { source: [] }
seen = set()
changes = 1
while todo:
next = {}
for stop in todo:
seen.add(stop)
busses = todo[stop]
for b in stop2bus[stop]:
if b in busses:
continue
for r in routes[b]:
if r == target:
return changes
if r not in seen:
next[r] = busses + [ b ]
changes += 1
todo = next
return -1
Difficulty
and has an acceptance rate of about 47% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Hash Table
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The function numBusesToDestination determines the minimum number of bus transfers required to travel from a source stop to a target stop given a collection of bus routes. It treats each bus route as a set of stops and performs a breadth-first search (BFS) over stops, expanding outward one bus ride at a time. The algorithm returns 0 when the start and destination coincide, -1 when the destination cannot be reached, and otherwise the smallest number of buses needed.
Building the stop-to-bus index
A crucial early step creates a reverse index that maps every stop to the set of bus routes that serve it. This enables constant-time lookup of candidate buses from any stop.
stop2bus = defaultdict(set)
for bus, stops in enumerate(routes):
for s in stops:
stop2bus[s].add(bus)
Using defaultdict(set) eliminates the need for explicit existence checks while populating the index, and the inner loop adds each bus identifier to the set associated with a stop.
Handling trivial and impossible cases
The function first checks whether the traveler is already at the destination:
if source == target:
return 0
It then verifies that both the source and target appear in the constructed index. If either stop is absent from all routes, the journey is impossible and -1 is returned:
if source not in stop2bus:
return -1
if target not in stop2bus:
return -1
These guards prevent unnecessary work and correctly handle edge conditions where the input data does not contain the required stops.
BFS frontier representation
The search frontier is stored in a dictionary named todo. The keys are stops that are reachable with the current number of bus changes, and the values are lists of bus identifiers already taken to reach that stop. The initial frontier contains only the source stop with an empty bus list:
todo = { source: [] }
A seen set records stops that have already been processed, ensuring that each stop is expanded at most once. The variable changes counts how many bus rides have been taken so far, starting at 1 because the first expansion corresponds to boarding the first bus.
Expanding the frontier
The main loop continues while there are stops to explore. For each stop in the current frontier, the algorithm marks it as processed and retrieves the list of buses already used to arrive there:
while todo:
next = {}
for stop in todo:
seen.add(stop)
busses = todo[stop]
For every bus that serves the current stop, the code skips buses that are already part of the path to avoid redundant transfers:
for b in stop2bus[stop]:
if b in busses:
continue
If a new bus is considered, the algorithm iterates over all stops on that bus route. When the target stop is encountered, the current changes value represents the minimal number of buses required, and the function returns it immediately:
for r in routes[b]:
if r == target:
return changes
Stops that have not yet been visited are added to the next frontier, together with the updated list of buses taken (the previous list plus the newly boarded bus). This construction preserves the exact sequence of buses used to reach each stop, which is essential for the duplicate-bus check described earlier:
if r not in seen:
next[r] = busses + [ b ]
After all stops in the current frontier have been processed, the changes counter is incremented to reflect the additional bus transfer, and the todo dictionary is replaced with the newly built next frontier:
changes += 1
todo = next
If the loop exits without finding the target, the function concludes that the destination is unreachable and returns -1.
Edge-case handling
The implementation gracefully manages several subtle situations:
- When the source and target are identical, the early equality check returns
0without further computation. - If either the source or target does not appear in any route, the function detects this via the
stop2busindex and returns-1. - Stops that belong to multiple routes are correctly represented in the
stop2busmapping, allowing the BFS to consider all possible transfers from a single location. - The
seenset prevents the algorithm from revisiting stops that have already been expanded, which avoids infinite loops in cases where routes form cycles. - By checking
if b in bussesbefore exploring a bus, the code avoids re-boarding the same bus on a later step, which could otherwise create unnecessary paths and inflate the transfer count.
Performance-focused design choices
Several aspects of the code contribute to efficient execution:
- The reverse index (
stop2bus) provides O(1) access to the set of buses serving any stop, eliminating the need for linear scans of all routes during expansion. - Storing the frontier as a dictionary keyed by stops ensures that each stop appears at most once per BFS layer, preventing duplicate work when multiple paths converge on the same stop.
- The
seenset acts as a global visited marker, guaranteeing that each stop is processed only a single time throughout the entire search, which bounds the total number of expansions by the number of distinct stops. - The early return upon encountering the target stop cuts the search short as soon as the optimal number of transfers is discovered, avoiding unnecessary exploration of deeper layers.
- The use of list concatenation (
busses + [ b ]) to build the path of buses for each newly discovered stop is performed only when a stop is first reached, keeping the overhead proportional to the number of unique stops rather than the total number of possible paths.
Overall, the algorithm combines a concise reverse lookup structure with a disciplined BFS that leverages set and dictionary operations to achieve fast identification of the minimal bus transfer count.
ELI5 - Simplified Explanation
Imagine a giant map filled with bus stops. Each bus follows a specific path that stops at several of these locations. The code acts like a helper who wants to find the shortest trip from the place where standing to the destination.
First, the computer organizes all the information by looking at every bus and figuring out which stops each one visits. It keeps a list of which buses go to which stops to make looking them up very quick.
Next, the computer begins a search. It starts at the current stop and looks at every bus line that passes through there. It peeks at every other shop those buses visit. If the destination is among those new stops, the trip is finished. If not, the computer looks at all the new stops it can reach and gets ready to check the ones visited by other buses branching out from there.
It keeps track of every place already checked so it does not get stuck going in circles. With every jump to a new bus, it counts one more step in the journey. The process repeats, hopping from bus to bus, until it finally finds the stop that is the goal. If there is no way to connect the buses to reach the final spot, the helpful search stops and reports that the destination cannot be reached.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | Java | C++ | Python | TS | ||||||
| WalkCCC | Java | C++ | Python | ||||||||
| leetcode.ca | Java | C++ | Python | Go | C# | TS | |||||
| LeetcodeHelp | Java | C++ | Python | ||||||||
| Progiez | Java | C++ | Python | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fengvyi | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| martianoff | Scala | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | Python | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fengvyi | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| martianoff | Scala | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | Python | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 2361: Minimum Costs Using the Train Line
Solved On The Same Day
- problem 812: Largest Triangle Area
- problem 824: Goat Latin
- problem 844: Backspace String Compare
- problem 791: Custom Sort String
- problem 794: Valid Tic-Tac-Toe State
- problem 807: Max Increase to Keep City Skyline
- problem 813: Largest Sum of Averages
- problem 814: Binary Tree Pruning
- problem 825: Friends Of Appropriate Ages
- problem 848: Shifting Letters
- problem 849: Maximize Distance to Closest Person
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality