Data Structures & AlgorithmsVery hardProduct Company SDE · greedy round

Problem: A circular route has gas = [1, 2, 3, 4, 5] and cost = [3, 4, 5, 1, 2] (cost to travel from station i to i+1). Find the start station index from which a full loop is possible, by running this code.

Problem: A circular route has gas = [1, 2, 3, 4, 5] and cost = [3, 4, 5, 1, 2] (cost to travel from station i to i+1). Find the start station index from which a full loop is possible, by running this code.
def start(gas, cost):
    tot = cur = s = 0
    for i in range(len(gas)):
        d = gas[i] - cost[i]
        tot += d
        cur += d
        if cur < 0:
            s = i + 1
            cur = 0
    return s if tot >= 0 else -1
print(start([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]))
What is printed?
  1. A. 0
  2. B. 3
  3. C. 4
  4. D. 2

Correct answer: B. 3

Stations 0, 1, 2 leave the running fuel negative, so the start moves to station 3, where the cumulative fuel never drops below zero. The total gas equals the total cost, so the loop is feasible from that start.

More Coding Interview Problems questions

Exams that ask this topic