Count All Possible Routes - Problem

You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.

At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x.

Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).

Return the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 10⁹ + 7.

Input & Output

Example 1 — Basic Case
$ Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5
Output: 4
💡 Note: Starting at city 1 (position 3) with 5 fuel, there are 4 possible routes to reach city 3 (position 8): 1→3 (cost 5), 1→0→3 (cost 1+6=7 > 5, invalid), 1→2→3 (cost 3+2=5), 1→4→3 (cost 1+4=5), and 1→4→0→3 (partial route within fuel limit).
Example 2 — Direct Route Only
$ Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6
Output: 5
💡 Note: From city 1 (position 3) to city 0 (position 4) with 6 fuel, multiple paths exist including detours through city 2.
Example 3 — Insufficient Fuel
$ Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3
Output: 0
💡 Note: From city 0 (position 5) to city 2 (position 1) requires 4 fuel minimum, but we only have 3.

Constraints

  • 2 ≤ locations.length ≤ 100
  • 1 ≤ locations[i] ≤ 109
  • All integers in locations are distinct
  • 0 ≤ start, finish < locations.length
  • 1 ≤ fuel ≤ 200

Visualization

Tap to expand
Count All Possible Routes with Fuel Constraint10234STARTFINISHpos=3pos=2pos=4pos=6pos=8Multiple routes possible: direct and with detoursFuel cost = |position[i] - position[j]|Count all valid paths that end at finish cityResult: 4 possible routes
Understanding the Visualization
1
Input
Cities at different positions with fuel limit
2
Process
Try all possible paths considering fuel costs
3
Output
Count of valid routes from start to finish
Key Takeaway
🎯 Key Insight: Same city with same remaining fuel always has the same number of possible routes to finish
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 5
38.5K Views
Medium 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