A car travels from a starting position to a destination which is target miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.
Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.
Example 1:
Input: target = 1, startFuel = 1, stations = [] Output: 0 Explanation: We can reach the target without refueling.
Example 2:
Input: target = 100, startFuel = 1, stations = [[10,100]] Output: -1 Explanation: We can not reach the target (or even the first gas station).
Example 3:
Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]] Output: 2 Explanation: We start with 10 liters of fuel. We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas. Then, we drive from position 10 to position 60 (expending 50 liters of fuel), and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target. We made 2 refueling stops along the way, so we return 2.
Constraints:
1 <= target, startFuel <= 1090 <= stations.length <= 5001 <= positioni < positioni+1 < target1 <= fueli < 109Problem Overview: You start with some fuel and must reach a target distance. Along the way are gas stations, each providing a fixed amount of fuel. The task is to determine the minimum number of refueling stops required to reach the target, or return -1 if the journey is impossible.
Approach 1: Dynamic Programming (O(n^2) time, O(n) space)
This method tracks the farthest distance reachable using exactly k refueling stops. Maintain a DP array where dp[k] stores the maximum distance you can travel after refueling k times. Iterate through each station and update the array backward so previous results are not overwritten. If you can reach a station with k stops, update dp[k+1] with the additional fuel from that station. After processing all stations, the smallest k where dp[k] ≥ target is the answer. This approach models the decision process clearly and works well when demonstrating state transitions using dynamic programming. The downside is quadratic time complexity for large station lists.
Approach 2: Greedy with Max Heap (O(n log n) time, O(n) space)
The optimal strategy uses a greedy idea: always refuel at the largest fuel station among those you have already passed when you run out of fuel. As you travel toward the target, push the fuel amounts of reachable stations into a max heap. When your current fuel is insufficient to move further, pop the largest fuel value from the heap and refuel. Each pop represents a refueling stop. This works because choosing the largest available refill maximizes how far you can continue without increasing the number of stops. The heap efficiently retrieves the best station in O(log n) time. This technique combines greedy algorithms with a heap (priority queue) to dynamically choose the best previous station.
Implementation typically iterates through stations sorted by distance (already provided that way). Track your current reachable distance and add stations to the heap once they become reachable. If the heap becomes empty before reaching the target, the trip is impossible.
Recommended for interviews: The greedy max heap solution is what interviewers expect. It reduces the problem to repeatedly choosing the best past option and achieves O(n log n) time. Mentioning the DP formulation first demonstrates understanding of the state space, but implementing the heap-based greedy approach shows stronger algorithmic optimization skills.
This approach leverages a greedy strategy with a max heap to ensure that whenever we're out of fuel, we choose to refuel from the station that offers the most fuel, maximizing our reach.
We traverse through the list of stations, when we reach a station, we check if we need to refuel (i.e., if our current fuel can't get us to the next station). If so, we refuel from the stations we've passed (choosing the one with the most fuel available). We keep track of the number of stops and return that as our result once we reach the target, or return -1 if it's not possible to reach the target.
This C solution uses an array to mimic a max-heap, replacing the max-heap functionality with a manually sorted insertion. Fuel from each station is added to the heap whenever it is reachable. We keep refueling from the station with maximum fuel until we reach the target or run out of options.
Time Complexity: O(n log n), as each insertion into the heap takes O(log n), and we perform this operation n times.
Space Complexity: O(n), storing the maximum fuel to be reused in a max-heap equivalent array.
In this approach, we use dynamic programming to track the maximum distance reached with a given number of refuel stops. By simulating the range expansions step-by-step at each station, we keep updating our maximum reach for each refuel stop count.
This works by creating an array dp where dp[i] stands for the farthest distance we can reach with i stops. Initially, dp[0] is initialized with startFuel, and the rest are kept at zero. As we iterate through the stations, we update this dp array backwards so as not to overwrite data prematurely. For each station, we update the dp array to reflect the best possible distance for each number of stops, which includes potentially refueling at that station.
This solution makes use of a dynamic programming array to update our fuel positions iteratively for each station. The backwards iteration allows evaluating each possibility of reaching a station, managing cumulative refueling statuses effectively and efficiently.
Time Complexity: O(n^2), as each station iterates over previous positions in potentially worst-case scenarios.
Space Complexity: O(n), where n is the station count and the dp array stores potential distances.
We can use a priority queue (max-heap) pq to record the fuel amounts of all the gas stations we have passed. Each time the fuel is insufficient, we greedily take out the maximum fuel amount, which is the top element of pq, and accumulate the number of refuels ans. If pq is empty and the current fuel is still insufficient, it means we cannot reach the destination, and we return -1.
The time complexity is O(n times log n), and the space complexity is O(n). Here, n represents the number of gas stations.
| Approach | Complexity |
|---|---|
| Greedy Approach using Max Heap | Time Complexity: O(n log n), as each insertion into the heap takes O(log n), and we perform this operation n times. Space Complexity: O(n), storing the maximum fuel to be reused in a max-heap equivalent array. |
| Dynamic Programming Approach | Time Complexity: O(n^2), as each station iterates over previous positions in potentially worst-case scenarios. Space Complexity: O(n), where n is the station count and the dp array stores potential distances. |
| Greedy + Priority Queue (Max-Heap) | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Dynamic Programming | O(n^2) | O(n) | When explaining state transitions or building intuition about how refueling choices affect reachable distance |
| Greedy with Max Heap | O(n log n) | O(n) | Best general solution for interviews and large inputs; efficiently selects the largest previous fuel station |
Minimum Number of Refueling Stops | Live Coding with Explanation | Leetcode - 871 • Algorithms Made Easy • 13,587 views views
Watch 9 more video solutions →Practice Minimum Number of Refueling Stops with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor