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

Problem: A car starts with an empty tank at one of n petrol pumps on a circular route; pump i gives gas[i] and the trip to the next costs cost[i]. Return the start index that completes the circuit, or −1.

Problem: A car starts with an empty tank at one of n petrol pumps on a circular route; pump i gives gas[i] and the trip to the next costs cost[i]. Return the start index that completes the circuit, or −1.
def start(gas, cost):
    if sum(gas) < sum(cost): return -1
    tank = s = 0
    for i in range(len(gas)):
        tank += gas[i] - cost[i]
        if tank < 0:
            s, tank = i + 1, 0
    return s
print(start([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]), start([2, 3, 4], [3, 4, 3]))
What is printed?
  1. A. 4 -1
  2. B. 3 0
  3. C. 0 -1
  4. D. 3 -1

Correct answer: D. 3 -1

If the total gas covers the total cost, a solution exists, and it is right after the last point where the running tank went negative (no start before that can pass it). Running balance: −2, −4, −6 → reset to start 3; then +3, +6. Second case: total 9 < 10 → −1. O(n), one pass.

More Coding Interview Problems questions

Exams that ask this topic