SDE & MLE Prep

871. Minimum Number of Refueling Stops

Problem

A car drives toward target miles away, starting with startFuel litres and burning 1 litre per mile. stations[i] = [position, fuel] lists gas stations in order of position; at a station you may take all of its fuel. Return the minimum number of refuelling stops to reach the target, or −1 if it's unreachable. Arriving anywhere with 0 fuel left still counts.

Example: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]] → 2

Constraints: up to 500 stations.

Drive as far as the fuel allows, pushing every station passed into a max-heap. When stuck, retroactively refuel at the biggest station passed (one stop). Fail if the heap is empty.

Complexity: O(n log n).

class Solution:
    def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:
        h, reach, i, stops = [], startFuel, 0, 0
        while reach < target:
            while i < len(stations) and stations[i][0] <= reach:
                heappush(h, -stations[i][1])
                i += 1
            if not h:
                return -1
            reach -= heappop(h)
            stops += 1
        return stops