LeetCode 815, Hard. Topics: Array, Hash Table, Breadth-First Search. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:
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.
Examples
Constraints
- 1 <= routes.length <= 500
- 1 <= routes[i].length <= 10^5
- All the values of
routes[i] are unique.
- sum(routes[i].length) <= 10^5
- 0 <= routes[i][j] < 10^6
- 0 <= source, target < 10^6
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Grind, NeetCode All. Last modified on September 7, 2026