CodeArchon

mediumGreedyAmazonFacebook

Petrol Loop Picker

A tour organizer picks the only starting gas station from which the vehicle can complete the circular route.

Given gas[i] and cost[i] for each station, return the start index to complete one full clockwise trip, or -1 if impossible.

Choose approach

1
0
i
2
1
start
3
2
4
3
5
4
Mapbalance
diff→-2
tank→0
total→-2
1/6
Narrationstep 1 of 6

i=0: gas-cost=-2, tank=0, total=-2 → reset start=1.

1def canCompleteCircuit(gas, cost):
2 total = tank = start = 0
3 for i in range(len(gas)):
4 d = gas[i] - cost[i]
5 total += d; tank += d
6 if tank < 0:
7 start = i + 1; tank = 0
8 return start if total >= 0 else -1
Variables
i=0
diff=-2
tank=0
total=-2
start=1

How to think about it

  1. sum(gas-cost) >= 0 is necessary and sufficient for feasibility.
  2. Reset trick skips all impossible starts in O(1).

Edge cases to catch in interview

  • Deficit total -> -1.
  • Single station with gas ≥ cost -> 0.

Examples

Example 1-1
{"gas":[2,3,4],"cost":[3,4,3],"values":[2,3,4]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed