Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the minimum number of refuelling stops to travel a distance, given stations (position, fuel) and start fuel.

Problem: Find the minimum number of refuelling stops to travel a distance, given stations (position, fuel) and start fuel.
import heapq
def stops(target, fuel, stations):
    h, i, n, cnt = [], 0, len(stations), 0
    while fuel < target:
        while i < n and stations[i][0] <= fuel:
            heapq.heappush(h, -stations[i][1]); i += 1
        if not h: return -1
        fuel += -heapq.heappop(h); cnt += 1
    return cnt
print(stops(100, 10, [[10, 60], [20, 30], [30, 30], [60, 40]]), stops(100, 1, [[10, 100]]), stops(1, 1, []))
What is printed?
  1. A. 3 -1 0
  2. B. 2 1 0
  3. C. 2 -1 1
  4. D. 2 -1 0

Correct answer: D. 2 -1 0

Drive as far as fuel allows, remembering every station passed in a max-heap; when stuck, retroactively refuel at the biggest one passed. 10 → take 60 (reach 70) → take 40 (reach 110): 2 stops. With 1 unit you never reach position 10 → −1. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic