Count All Possible Routes - Problem
Fuel-Constrained City Travel

Imagine you're planning a road trip across several cities with limited fuel! ๐Ÿš—โ›ฝ

You're given an array locations where locations[i] represents the position of city i on a straight highway. You start at city start with fuel units of gas and want to reach city finish.

Travel Rules:
โ€ข You can move from any city i to any other city j (except the same city)
โ€ข Moving from city i to city j costs |locations[i] - locations[j]| fuel
โ€ข You can revisit cities multiple times (including start and finish)
โ€ข Your fuel can never go negative

Goal: Count all possible routes from start to finish with your available fuel. Since the answer can be huge, return it modulo 109 + 7.

This is a classic dynamic programming problem that tests your ability to handle state transitions with constraints!

Input & Output

example_1.py โ€” Basic Route Counting
$ Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5
โ€บ Output: 4
๐Ÿ’ก Note: There are 4 possible routes: 1โ†’3 (direct), 1โ†’0โ†’3, 1โ†’2โ†’3, and 1โ†’4โ†’3. Each uses โ‰ค5 fuel units.
example_2.py โ€” Limited Fuel
$ Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6
โ€บ Output: 5
๐Ÿ’ก Note: Routes: 1โ†’0, 1โ†’2โ†’0, 1โ†’0โ†’2โ†’0, 1โ†’2โ†’1โ†’0, 1โ†’0โ†’1โ†’0. All fit within 6 fuel units.
example_3.py โ€” No Valid Routes
$ Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3
โ€บ Output: 0
๐Ÿ’ก Note: Cannot reach city 2 from city 0 with only 3 fuel (minimum distance is 4).

Constraints

  • 2 โ‰ค locations.length โ‰ค 100
  • 1 โ‰ค locations[i] โ‰ค 109
  • All locations[i] are distinct
  • 0 โ‰ค start, finish < locations.length
  • 1 โ‰ค fuel โ‰ค 200

Visualization

Tap to expand
DP State TransitionsSTARTfuel=10C1C2C3FINISHroutes=1Memoization TableState (City, Fuel) โ†’ Routes Count(START, 10) โ†’ 5 routes(C1, 7) โ†’ 3 routes(C2, 6) โ†’ 2 routes(C3, 4) โ†’ 1 route(FINISH, any) โ†’ 1 routeโœ“ Avoid Recomputation
Understanding the Visualization
1
State Definition
Each (city, remaining_fuel) represents a unique state
2
Transition
From each state, try moving to all other cities if fuel allows
3
Base Case
If current city equals finish, count this as one valid route
4
Memoization
Cache results to avoid recalculating the same state
Key Takeaway
๐ŸŽฏ Key Insight: Memoization transforms exponential route exploration into polynomial-time computation by caching results for each (city, fuel) state.
Asked in
Google 28 Amazon 22 Meta 18 Microsoft 15
28.0K Views
Medium-High Frequency
~25 min Avg. Time
892 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