Python 1575.py
class Solution:
def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:
# use absolute positions instead of city IDs
start = locations[start]
finish = locations[finish]
# sort cities to allow the use of fast binary search in deeper()
locations.sort()
@cache
def deeper(pos, gas): # ways to reach finish from pos with certain amount of fuel
if gas < 0: # out of gas
return 0
result = 0
if pos == finish:
result = 1 # made it to the finish line ...
# but it's possible to drive back to some city and then return to finish
# therefore we MUST NOT return 1 at this point
# determine range
a = bisect_left (locations, pos - gas)
b = bisect_right(locations, pos + gas)
# scan all cities in that range
for l in locations[a : b]:
if l != pos:
distance = abs(l - pos)
result += deeper(l, gas - distance)
return result % 1_000_000_007
return deeper(start, fuel)
Difficulty
and has an acceptance rate of about 65% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Memoization
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 countRoutes method computes the number of possible journeys from a starting city to a destination city given a limited amount of fuel. Each city is identified by its coordinate on a line, and a move between two cities consumes fuel equal to the absolute distance between their coordinates. The result is returned modulo 1 000 000 007. The implementation relies on depth-first exploration with memoization and leverages sorted coordinates to prune the search space efficiently.
Key Steps
Transforming indices to coordinates
start = locations[start]
finish = locations[finish]
The input provides the start and finish as indices into the locations list. Converting them to their absolute positions simplifies subsequent distance calculations.
Sorting the city coordinates
locations.sort()
Sorting enables binary search to quickly locate the subset of cities that lie within the current fuel range. The order of cities after sorting does not affect correctness because only distances matter.
Memoized recursive exploration
@cache
def deeper(pos, gas):
if gas < 0:
return 0
result = 0
if pos == finish:
result = 1
a = bisect_left(locations, pos - gas)
b = bisect_right(locations, pos + gas)
for l in locations[a:b]:
if l != pos:
distance = abs(l - pos)
result += deeper(l, gas - distance)
return result % 1_000_000_007
The inner function deeper returns the number of ways to reach the destination from a given position pos with gas units of fuel remaining. The @cache decorator stores previously computed results, turning the exponential recursion into a polynomial-time dynamic programming solution.
Determining the reachable interval
a = bisect_left(locations, pos - gas)
b = bisect_right(locations, pos + gas)
Using bisect_left and bisect_right on the sorted list yields the indices of the first city not less than pos-gas and the first city greater than pos+gas. All cities between a (inclusive) and b (exclusive) are reachable with the current fuel amount.
Iterating over reachable cities
for l in locations[a:b]:
if l != pos:
distance = abs(l - pos)
result += deeper(l, gas - distance)
Each reachable city l that is distinct from the current position is considered as the next step. The fuel consumption for the move is subtracted, and the recursive call accumulates the number of routes from the new state.
Returning the final answer
return deeper(start, fuel)
The outer call initiates the recursion from the starting coordinate with the full fuel budget.
Edge Cases Handled
When the remaining fuel becomes negative, the function immediately returns zero, preventing any further exploration from an impossible state. If the current position coincides with the destination, the function counts the current path as a valid route by setting result to one. Importantly, the recursion does not terminate at this point; additional moves that leave the destination and later return are still explored, ensuring that all routes that pass through the finish multiple times are counted.
If the fuel amount is zero, the binary search interval collapses to the exact position, and the loop over reachable cities yields no iterations because the condition l != pos excludes the current city. Consequently, only the direct finish-at-start case contributes a count of one when start == finish.
Sorting the locations list also normalizes duplicate coordinates. The binary search range includes all duplicates, but the if l != pos guard prevents a zero-distance self-loop, thereby avoiding infinite recursion while still allowing transitions between distinct cities that share the same coordinate.
Performance Optimizations
The primary optimization stems from sorting the city coordinates and using binary search (bisect_left and bisect_right) to restrict the recursive loop to cities that are actually reachable with the available fuel. This reduces the number of recursive calls from a potential scan of the entire list to a scan of a bounded interval whose size is proportional to the fuel range.
Memoization via @cache eliminates repeated computation of identical subproblems. Each unique pair (pos, gas) is evaluated at most once, turning the naive exponential search into a dynamic programming solution whose runtime grows with the number of distinct states rather than the number of possible paths.
Applying the modulo operation only at the return point of each recursive call keeps intermediate sums within the range of Python integers while guaranteeing that the final result conforms to the required modulus.
Together, these techniques ensure that the algorithm scales efficiently even for large inputs, leveraging ordering, pruning, and caching to achieve a fast and memory-conservative solution.
ELI5 - Simplified Explanation
Imagine there is a toy car sitting on a long track with many stations along the way. Each station has a special number that tells the car exactly where it is. To make things easy, the car lines up all the stations in order from smallest to biggest so it knows exactly which ones are nearby.
The car has a tank of fuel, and it needs to find every possible path to reach the finish line. Because it likes to be very thorough, it plans to check every path it can take. When the car is at a station, it looks at how much fuel it has left and figures out which other stations it can reach before running out of gas.
If the car reaches the finish line, it marks that as a successful trip. However, the car is clever, so it does not stop there. It remembers that it could also drive away from the finish line to a different station and try to come back again if it still has enough fuel left.
To keep track of all these adventures, the car uses a magical notepad. Whenever it plans a trip from a certain station with a specific amount of fuel, it checks the notepad. If it has already figured out how many ways there are to finish the journey from that spot with that much fuel, it just looks at its notes instead of doing all the math over again.
Because there can be a huge number of paths, the car uses a big counting rule to keep the final answer from getting too cluttered. It keeps trying every jump until it runs out of possible moves, adding up all the ways it successfully touched the finish line to get the final count.
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 | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Java | Go | Python | TS | |||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1694: Reformat Phone Number
- problem 1664: Ways to Make a Fair Array
- problem 1665: Minimum Initial Energy to Finish Tasks
- problem 1691: Maximum Height by Stacking Cuboids
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