Minimum Number of Refueling Stops (LeetCode 871): Solution and Explanation

Hard
Array
Dynamic Programming
Greedy
Heap

A car drives east toward a target with some starting fuel, burning one liter per mile, and passes gas stations at known positions with known amounts of fuel. Return the fewest stops needed to reach the target, or -1 if it cannot be reached.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A natural first idea is to stop at the next station whenever fuel runs low, but that is wrong: a small station now might be followed by a huge one that we cannot quite reach. A DP over stations works, tracking the farthest distance reachable with exactly t stops, but there is a cleaner greedy once we change how we think about stopping.

Imagine driving with a magic trunk. Every time we pass a station, we do not decide anything yet; we just remember how much fuel it offered. Only when the tank is about to run dry do we look back and pretend we had stopped at one of the stations we passed. Which one? The one with the most fuel, because every stop costs the same and the biggest refill pushes us farther than any other single stop could. Retroactively choosing is legal because any station we passed was reachable at the time.

A max heap holds the fuel amounts of stations already passed. The loop is: while fuel does not reach the target, push every station whose position is within current fuel range, then pop the largest amount and add it to the fuel, counting one stop. If the heap is empty when we need fuel, no choice of stations can get us further, so the answer is -1. Since fuel measures the farthest point reachable, it doubles as the position bound for which stations count as passed.

Approach: Greedy with a max heap

  1. Set fuel = startFuel, stops = 0, a station pointer i = 0 and an empty max heap (stored as negated values in Python).
  2. Loop while fuel < target.
  3. Push the fuel of every station with stations[i][0] <= fuel, advancing i, since all of them are reachable.
  4. If the heap is empty, no reachable station is left to use, so return -1.
  5. Pop the largest fuel amount, add it to fuel and increment stops.
  6. When fuel reaches the target, return stops.

Step-by-step example

target = 100, startFuel = 10, stations = [[10,60], [20,30], [30,30], [60,40]]
  1. fuel = 10 is less than 100. The station at position 10 is reachable, so push 60. The heap is {60}.
  2. Pop 60: fuel = 70, stops = 1.
  3. fuel = 70 is still less than 100. Stations at 20, 30 and 60 are now within reach, so push 30, 30 and 40.
  4. Pop the largest, 40: fuel = 110, stops = 2.
  5. fuel = 110 covers the target, so the loop ends and the answer is 2 (refuel at 10 and at 60).

Code: Python, Java, C++

1class Solution:
2    def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
3        # Max heap to store fuel amounts we can take
4        maxHeap = []
5        fuel = startFuel
6        stops = 0
7        i = 0
8
9        while fuel < target:
10            # Add all reachable stations to heap
11            while i < len(stations) and stations[i][0] <= fuel:
12                heapq.heappush(maxHeap, -stations[i][1])
13                i += 1
14
15            # If no stations reachable and can't reach target
16            if not maxHeap:
17                return -1
18
19            # Refuel with max fuel available
20            fuel += -heapq.heappop(maxHeap)
21            stops += 1
22
23        return stops

Time and space complexity

Time

O(n log n)

Each of the n stations is pushed onto the heap at most once and popped at most once, and each heap operation costs O(log n).

Space

O(n)

The heap can hold every station when they are all reachable before the first refuel.

Other approaches

DP on number of stops (time O(n²), space O(n))

Let dp[t] be the farthest position reachable using t stops. For each station in order, update dp[t + 1] from dp[t] for every t from high to low whenever dp[t] reaches that station. The answer is the smallest t with dp[t] >= target. It is easy to prove correct but slower.

Common mistakes

  • Refueling at every station passed, or at the nearest one, instead of only when necessary and from the largest option.
  • Using a min heap in Python without negating values, which picks the smallest refill instead of the largest.
  • Comparing station positions against remaining fuel rather than total distance reachable. In this formulation fuel is the reachable distance.
  • Returning -1 when fuel is exactly zero at a station. Arriving with zero fuel still counts as reaching that station.

Frequently asked questions

Why is the greedy choice of the largest station correct?

Every stop costs exactly one. Among stations we could have stopped at, taking the one with the most fuel maximizes how far we can get, and any later decision available after a smaller refill is also available after the larger one.

Why can we pick a station after we have already driven past it?

We only pop stations that were reachable, so stopping there was possible at the time. Deferring the decision just lets us see more options before committing, without changing what is physically possible.

Is the DP or the heap solution better?

The heap solution is O(n log n) and shorter. The DP is O(n²), which still passes for n up to 500, and some people find its correctness easier to argue.

What if the starting fuel already covers the target?

The while loop never runs and the function returns 0 stops. No stations are pushed or examined at all, which is the correct answer since the car can drive straight there.