ProgrammingHardAccenture · Cognizant

Gas stations on a circle: gas = [1,2,3,4,5], cost = [3,4,5,1,2]. Station i gives gas[i] and then costs cost[i] to leave for station i+1. The total gas equals the total cost, so a full tour exists from exactly one start. The procedure below finds it. What is printed?

Gas stations on a circle: gas = [1,2,3,4,5], cost = [3,4,5,1,2]. Station i gives gas[i] and then costs cost[i] to leave for station i+1. The total gas equals the total cost, so a full tour exists from exactly one start. The procedure below finds it. What is printed?
total = 0; tank = 0; start = 0
for i = 0 to 4
    tank = tank + gas[i] - cost[i]
    total = total + gas[i] - cost[i]
    if tank < 0 then start = i + 1; tank = 0
end for
Print start
  1. A. 0
  2. B. 3
  3. C. 2
  4. D. 4

Correct answer: B. 3

Once the tank goes negative no station between the old start and i can start a valid tour, so the start moves to i+1 and the tank resets. Starting at 0 ignores the failed stretch, resetting to i instead of i+1 restarts a station too early, and not resetting the tank carries a deficit forward.

More Pseudocode and Code Tracing questions

Exams that ask this topic