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?- A. 3 -1 0
- B. 2 1 0
- C. 2 -1 1
- 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
- Problem: A printer raises ink levels by choosing any contiguous block of cartridges and adding 1 unit to each in one operation. Starting…
- Problem: Count contiguous subarrays whose max − min ≤ k, using two monotonic deques and a shrinking left edge. python from collections…
- Problem: Return the k-th smallest absolute difference among all pairs of readings (n up to 10⁵, so the n² pairs cannot be listed). Binary…
- Problem: Tasks of given lengths must be packed into work sessions of at most T = 8 hours; a task cannot be split. Exact bitmask DP (state…
- Problem: Paint a 3 × n wall: each cell gets one of 3 colours and side-adjacent cells must differ. Count valid colourings by DP over row…
- Problem: Each event (start day, end day) can be attended on any ONE day in its range, and you can attend at most one event per day…