Skip to main content

Count All Possible Routes - Solution & Explanation

Practice this problem

Problem Statement

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 109 + 7.

 

Example 1:

Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5
Output: 4
Explanation: The following are all possible routes, each uses 5 units of fuel:
1 -> 3
1 -> 2 -> 3
1 -> 4 -> 3
1 -> 4 -> 2 -> 3

Example 2:

Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6
Output: 5
Explanation: The following are all possible routes:
1 -> 0, used fuel = 1
1 -> 2 -> 0, used fuel = 5
1 -> 2 -> 1 -> 0, used fuel = 5
1 -> 0 -> 1 -> 0, used fuel = 3
1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5

Example 3:

Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3
Output: 0
Explanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.

 

Constraints:

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

Approach Overview

Problem Overview: You are given city locations on a line, a start city, a finish city, and a limited amount of fuel. Moving between cities costs fuel equal to the distance between them. Count how many different routes can reach the finish city without the fuel dropping below zero. Cities can be revisited multiple times.

Approach 1: Recursive Depth-First Search (Exponential Time)

This approach explores every possible path using recursion. From the current city, iterate through all other cities and move if the fuel cost abs(locations[i] - locations[j]) is affordable. Each recursive call represents traveling to another city with reduced fuel. Whenever the current city equals the finish city, increment the route count. Because cities can be revisited, the recursion generates many repeated states, leading to O(n^fuel) worst-case time with O(fuel) recursion stack space. This method helps understand the search space but quickly becomes too slow for large inputs.

Approach 2: Dynamic Programming with Memoization (O(n² * fuel))

The key observation: the state is fully defined by the current city and remaining fuel. If you reach the same city again with the same fuel, the number of routes from that state will always be the same. Use a memo table dp[city][fuel] to cache results. For each state, iterate through all other cities, compute the fuel cost, and recursively count routes if enough fuel remains. Add 1 whenever the current city equals the finish city. Memoization avoids recomputation and collapses the exponential search into O(n² * fuel) time with O(n * fuel) space. This technique is a classic combination of dynamic programming and memoization, where overlapping subproblems are cached during recursion.

The transition looks like: from city i, try traveling to city j. If fuel >= abs(locations[i] - locations[j]), add the result of dfs(j, fuel - cost). Store the result in the DP table so future calls reuse it instantly. The total route count is typically taken modulo 1e9+7 to avoid overflow.

Recommended for interviews: Dynamic Programming with memoization. Interviewers expect you to recognize overlapping subproblems and convert the brute-force DFS into a cached state search. Explaining the naive DFS first shows understanding of the problem space, while the DP optimization demonstrates strong problem-solving skills with arrays and state-based DP.

Approach 1: Dynamic Programming with Memoization

This approach involves using dynamic programming to keep track of the number of ways to reach the target city with the available fuel. We will define a DP table where dp[i][f] represents the number of ways to start from city i with f units of fuel left and reach the target city. We recursively fill this table while considering moves to any other city and subtracting the appropriate fuel cost for that move. The result will be stored in the dp[start][fuel] after exploring all possible routes.

The C solution uses a top-down dynamic programming approach with memoization. It initializes a 2D array (dp) to store the number of routes. The recursive function explores from the current city to possible destinations, decrementing the fuel and checking if it reaches the finish city. Modulo operation by 10^9 + 7 is applied to avoid overflow.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n * fuel * n), where n is the number of cities. This can be reduced using better states or pruning.
Space Complexity: O(n * fuel) for the dp table.

Try this approach in the editor →

Approach 2: Recursive Depth-First Search

In this approach, a depth-first search (DFS) is implemented to explore possible routes from the start to the finish city. Each travel option is a branch in the DFS tree, where the algorithm explores each choice of stopping at a different city until it no longer has fuel. The recursion keeps track of current fuel and updates the count whenever it reaches the finish city with valid fuel.

The C solution provides a direct recursive DFS approach without memoizing results. This traverses all possible pathways considering each move and updates the route count if successful. Uses modulo for result consistency.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^fuel) without pruning, given recursive branching per city. This complexity is potentially high without memoization.
Space Complexity: O(fuel) due to recursive call stack depth.

Try this approach in the editor →

Approach 3: Memoization

We design a function dfs(i, k), which represents the number of paths from city i with k remaining fuel to the destination finish. So the answer is dfs(start, fuel).

The process of calculating the function dfs(i, k) is as follows:

  • If k \lt |locations[i] - locations[finish]|, then return 0.
  • If i = finish, then the number of paths is 1 at the beginning, otherwise it is 0.
  • Then, we traverse all cities j. If j \ne i, then we can move from city i to city j, and the remaining fuel is k - |locations[i] - locations[j]|. Then we can add the number of paths to the answer dfs(j, k - |locations[i] - locations[j]|).
  • Finally, we return the number of paths to the answer.

To avoid repeated calculations, we can use memoization.

The time complexity is O(n^2 times m), and the space complexity is O(n times m). Where n and m are the size of the array locations and fuel respectively.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Approach 4: Dynamic Programming

We can also convert the memoization of solution 1 into dynamic programming.

We define f[i][k] represents the number of paths from city i with k remaining fuel to the destination finish. So the answer is f[start][fuel]. Initially f[finish][k]=1, others are 0.

Next, we enumerate the remaining fuel k from small to large, and then enumerate all cities i. For each city i, we enumerate all cities j. If j \ne i, and |locations[i] - locations[j]| \le k, then we can move from city i to city j, and the remaining fuel is k - |locations[i] - locations[j]|. Then we can add the number of paths to the answer f[j][k - |locations[i] - locations[j]|].

Finally, we return the number of paths to the answer f[start][fuel].

The time complexity is O(n^2 times m), and the space complexity is O(n times m). Where n and m are the size of the array locations and fuel respectively.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Dynamic Programming with Memoization

Time Complexity: O(n * fuel * n), where n is the number of cities. This can be reduced using better states or pruning.
Space Complexity: O(n * fuel) for the dp table.

Recursive Depth-First Search

Time Complexity: O(n^fuel) without pruning, given recursive branching per city. This complexity is potentially high without memoization.
Space Complexity: O(fuel) due to recursive call stack depth.

Memoization—
Dynamic Programming—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive Depth-First SearchExponential (ā‰ˆ O(n^fuel))O(fuel)Understanding the raw search space or explaining brute-force reasoning in interviews
Dynamic Programming with MemoizationO(n² * fuel)O(n * fuel)Optimal solution for constraints where cities and fuel states repeat frequently

Video Solution

Count All Possible Routes | Recur + Memo | Tree Diagram | ZOHO | Leetcode-1575 | Live Code • codestorywithMIK • 5,593 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Count All Possible Routes easy or hard?
Count All Possible Routes is classified as a Hard problem on LeetCode. The difficulty comes from recognizing the DP state (city, fuel) and handling repeated visits to cities without exponential recomputation.
Count All Possible Routes Python/Java solution
Both Python and Java solutions typically implement DFS with memoization. A recursive function explores possible next cities, stores results in a dp table, and returns cached results when the same state appears again.
How to solve Count All Possible Routes in O(n^2 * fuel)?
Use DFS with memoization. Define a function dfs(city, fuel) that returns the number of routes from that city with the remaining fuel. Cache results in a DP table and iterate through every other city to explore valid moves whose travel cost fits within the remaining fuel.
What is the best approach for Count All Possible Routes?
Dynamic Programming with memoization is the best approach. The state is defined by the current city and remaining fuel, and results are cached in a dp[city][fuel] table. This prevents recalculating identical states and reduces the complexity to O(n^2 * fuel).
Is Count All Possible Routes asked at Google/Amazon/Meta?
Dynamic programming problems involving state transitions and memoization frequently appear in interviews at companies like Google, Amazon, and Meta. This problem tests recognizing overlapping subproblems and designing an efficient DP state.
What data structure is used in Count All Possible Routes?
The main structure is a 2D dynamic programming array or memoization table dp[city][fuel]. Recursion or DFS is used to explore transitions, while the array caches previously computed states.
What is the time complexity of Count All Possible Routes?
The optimized solution runs in O(n^2 * fuel) time because for each state (city, remaining fuel) you iterate through all other cities. The space complexity is O(n * fuel) for the memoization table.

Ready to solve this problem?

Practice Count All Possible Routes with our built-in code editor and test cases.

Practice on FleetCode