Skip to main content

Minimum Number of Refueling Stops - Solution & Explanation

HardArrayDynamic ProgrammingGreedyHeap (Priority Queue)22 min readAsked at: Amazon, Microsoft, Uber +4
Practice this problem

Problem Statement

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 <= 109
  • 0 <= stations.length <= 500
  • 1 <= positioni < positioni+1 < target
  • 1 <= fueli < 109

Approach Overview

Problem 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.

Approach 1: Greedy Approach using Max Heap

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.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

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.

Try this approach in the editor →

Approach 2: Dynamic Programming Approach

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.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

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.

Try this approach in the editor →

Approach 3: Greedy + Priority Queue (Max-Heap)

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.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
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)—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Dynamic ProgrammingO(n^2)O(n)When explaining state transitions or building intuition about how refueling choices affect reachable distance
Greedy with Max HeapO(n log n)O(n)Best general solution for interviews and large inputs; efficiently selects the largest previous fuel station

Video Solution

Minimum Number of Refueling Stops | Live Coding with Explanation | Leetcode - 871 • Algorithms Made Easy • 13,834 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Minimum Number of Refueling Stops easy or hard?
Minimum Number of Refueling Stops is classified as a Hard problem because the optimal solution requires recognizing a greedy pattern combined with a priority queue. Many developers initially attempt dynamic programming before discovering the more efficient heap-based approach.
Minimum Number of Refueling Stops Python/Java solution
Most implementations use a priority queue to store fuel from reachable stations. In Python, a heap (often simulated as a max heap using negative values) is used. In Java or C++, a PriorityQueue or priority_queue provides efficient O(log n) insertion and removal for the greedy algorithm.
How to solve Minimum Number of Refueling Stops in O(n log n)?
Iterate through stations while tracking the maximum distance reachable with your current fuel. Add fuel amounts of reachable stations to a max heap. When you cannot move forward, pop the largest fuel value from the heap and refuel. Each heap pop counts as a stop, leading to an O(n log n) algorithm.
What is the best approach for Minimum Number of Refueling Stops?
The optimal approach uses a greedy strategy with a max heap (priority queue). As you pass stations, push their fuel amounts into the heap. Whenever your fuel is insufficient to continue, refuel using the largest available station from the heap. This ensures the fewest stops while running in O(n log n) time and O(n) space.
Is Minimum Number of Refueling Stops asked at Google/Amazon/Meta?
Minimum Number of Refueling Stops is a classic greedy and heap interview problem that has appeared in interviews at large tech companies including Google, Amazon, and Meta. It tests your ability to combine greedy decision making with a priority queue data structure.
What data structure is used in Minimum Number of Refueling Stops?
A max heap (priority queue) is the key data structure in the optimal solution. It stores fuel amounts from stations you have already passed, allowing you to quickly choose the largest available refuel option when your fuel becomes insufficient.
What is the time complexity of Minimum Number of Refueling Stops?
The greedy max heap solution runs in O(n log n) time because each station may be pushed and popped from the heap once. The dynamic programming alternative runs in O(n^2) time with O(n) space since it updates reachable distances for each possible number of stops.

Ready to solve this problem?

Practice Minimum Number of Refueling Stops with our built-in code editor and test cases.

Practice on FleetCode