ProgrammingVery hardInfosys HackWithInfy · TCS CodeVita

What is printed?

What is printed?
def can_complete(gas, cost):
    total = tank = start = 0
    for i in range(len(gas)):
        d = gas[i] - cost[i]
        total += d
        tank += d
        if tank < 0:
            start = i + 1
            tank = 0
    return start if total >= 0 else -1
print(can_complete([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]), can_complete([2, 3, 4], [3, 4, 3]))
  1. A. 2 -1
  2. B. -1 3
  3. C. 3 0
  4. D. 3 -1

Correct answer: D. 3 -1

If total gas is below total cost, no full circuit exists and the answer is -1. Otherwise the start moves past each failed tank, and in the first case the start is station 3.

More Python Programming questions

Exams that ask this topic