Magicsheet logo

Minimum Number of Refueling Stops

Hard
71%
Updated 6/1/2025

Minimum Number of Refueling Stops

1. What is this problem about?

In this hard-level problem, a car starts at a certain position with a specific amount of fuel. It needs to reach a target destination. Along the way, there are gas stations at various distances, each offering a certain amount of fuel. The car consumes 1 unit of fuel per unit of distance. You need to find the minimum number of stops required to reach the target. If the target is unreachable, return -1.

2. Why is this asked in interviews?

This is a flagship problem for companies like Google and Goldman Sachs. It's difficult because a simple greedy approach (stopping at the next station) doesn't work. It requires a sophisticated "lazy greedy" approach using a max-heap. It tests your ability to manage state and make optimal decisions based on future possibilities, which is a core skill for any backend or systems engineer.

3. Algorithmic pattern used

The most efficient pattern is the Greedy with a Max-Heap (Priority Queue) approach. As you drive, you pass gas stations. Instead of stopping immediately, you "collect" the fuel from every station you pass and store it in a max-heap. When you run out of fuel, you retroactively "stop" at the station with the most fuel you've passed so far. You repeat this until you have enough fuel to reach the next station or the target.

4. Example explanation

  • Target: 100, Start Fuel: 10.
  • Stations: [[10, 60], [20, 30], [30, 30]].
  • Drive to distance 10. Fuel = 0.
  • We passed station at 10 (has 60 fuel). Add 60 to heap.
  • Running out! Pop 60 from heap. Stop count = 1. Fuel = 60.
  • Now we can reach the next stations and the target easily. Minimum stops = 1.

5. Common mistakes candidates make

Many candidates try to solve this using Dynamic Programming, which is possible (O(n²)) but much slower than the Max-Heap approach (O(n log n)). Another common error is failing to add the final target check—forgetting that you might run out of fuel exactly at or before reaching the destination. Some also forget to handle the case where the heap is empty but the target hasn't been reached yet.

6. Interview preparation tip

The "Refueling Stops" problem is a perfect example of why you should always consider a Priority Queue when you need to "pick the best option from everything seen so far." Practice this "lazy greedy" logic, as it applies to many scheduling and resource management problems.

Similar Questions