Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 <= 1090 <= stations.length <= 5001 <= positioni < positioni+1 < target1 <= fueli < 109Problem summary: 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
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Greedy
1 1 []
100 1 [[10,100]]
100 10 [[10,60],[20,30],[30,30],[60,40]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #871: Minimum Number of Refueling Stops
class Solution {
public int minRefuelStops(int target, int startFuel, int[][] stations) {
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
int n = stations.length;
int ans = 0, pre = 0;
for (int i = 0; i <= n; ++i) {
int pos = i < n ? stations[i][0] : target;
int dist = pos - pre;
startFuel -= dist;
while (startFuel < 0 && !pq.isEmpty()) {
startFuel += pq.poll();
++ans;
}
if (startFuel < 0) {
return -1;
}
if (i < n) {
pq.offer(stations[i][1]);
pre = stations[i][0];
}
}
return ans;
}
}
// Accepted solution for LeetCode #871: Minimum Number of Refueling Stops
func minRefuelStops(target int, startFuel int, stations [][]int) int {
pq := &hp{}
ans, pre := 0, 0
stations = append(stations, []int{target, 0})
for _, station := range stations {
pos, fuel := station[0], station[1]
dist := pos - pre
startFuel -= dist
for startFuel < 0 && pq.Len() > 0 {
startFuel += heap.Pop(pq).(int)
ans++
}
if startFuel < 0 {
return -1
}
heap.Push(pq, fuel)
pre = pos
}
return ans
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
# Accepted solution for LeetCode #871: Minimum Number of Refueling Stops
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
// Accepted solution for LeetCode #871: Minimum Number of Refueling Stops
use std::collections::BinaryHeap;
impl Solution {
pub fn min_refuel_stops(target: i32, mut start_fuel: i32, mut stations: Vec<Vec<i32>>) -> i32 {
let mut pq = BinaryHeap::new();
let mut ans = 0;
let mut pre = 0;
stations.push(vec![target, 0]);
for station in stations {
let pos = station[0];
let fuel = station[1];
let dist = pos - pre;
start_fuel -= dist;
while start_fuel < 0 && !pq.is_empty() {
start_fuel += pq.pop().unwrap();
ans += 1;
}
if start_fuel < 0 {
return -1;
}
pq.push(fuel);
pre = pos;
}
ans
}
}
// Accepted solution for LeetCode #871: Minimum Number of Refueling Stops
function minRefuelStops(target: number, startFuel: number, stations: number[][]): number {
const pq = new MaxPriorityQueue<number>();
let [ans, pre] = [0, 0];
stations.push([target, 0]);
for (const [pos, fuel] of stations) {
const dist = pos - pre;
startFuel -= dist;
while (startFuel < 0 && !pq.isEmpty()) {
startFuel += pq.dequeue();
ans++;
}
if (startFuel < 0) {
return -1;
}
pq.enqueue(fuel);
pre = pos;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.