HardNo. 0871

Minimum Number of Refueling Stops — LeetCode 871 Python Solution

Topics
Greedy, Array, Dynamic Programming, Heap (Priority Queue)
Reading time
3 min

The problem

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.

Example

Input
target = 1, startFuel = 1, stations = []
Output
0
Explanation
We can reach the target without refueling.

Python solution

PythonSolution
class Solution:
    def minRefuelStops(
        self, target: int, startFuel: int, stations: List[List[int]]
    ) -> int:
        pq = []
        ans = pre = 0
        stations.append([target, 0])
        for pos, fuel in stations:
            dist = pos - pre
            startFuel -= dist
            while startFuel < 0 and pq:
                startFuel -= heappop(pq)
                ans += 1
            if startFuel < 0:
                return -1
            heappush(pq, -fuel)
            pre = pos
        return ans

Complexity

Time
O(n × log n)
Space · auxiliary
O(n)

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 871. Minimum Number of Refueling Stops is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
1388Pizza With 3n SlicesHard
0045Jump Game IIMedium
0055Jump GameMedium
0122Best Time to Buy and Sell Stock IIMedium
0376Wiggle SubsequenceMedium
0435Non-overlapping IntervalsMedium

Frequently asked questions

How hard is LeetCode 871. Minimum Number of Refueling Stops?

LeetCode 871. Minimum Number of Refueling Stops is rated Hard on LeetCode.

What is the time complexity of LeetCode 871. Minimum Number of Refueling Stops?

The Python solution on this page runs in O(n × log n).

What is the space complexity of LeetCode 871. Minimum Number of Refueling Stops?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 871. Minimum Number of Refueling Stops cover?

LeetCode 871. Minimum Number of Refueling Stops is tagged Greedy, Array, Dynamic Programming and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.