Find the station where you can drive the whole loop. If the total gas covers the total cost, an answer exists; whenever the tank goes negative, start again from the next station.
▼The problem
LeetCode 134 (Medium). n stations sit on a circular route; station i gives gas[i] fuel and driving from it to the next costs cost[i]. Starting with an empty tank, return the index of the station where you can start and drive the loop once, or -1 (the answer is unique if it exists).
Example: gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2] → 3.
def can_complete_circuit(gas, cost):
if sum(gas) < sum(cost):
return -1
start, tank = 0, 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start, tank = i + 1, 0
return startTRY IT ON LEETCODE ▶The solution
def can_complete_circuit(gas, cost):
if sum(gas) < sum(cost):
return -1
start, tank = 0, 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start, tank = i + 1, 0
return startTranscript
Gas Station. A circular road has n stations. Each one gives you some gas, and driving to the next one costs some. Start with an empty tank, and find the station where you can drive the whole loop once, or return minus one.
Here's an example. Gas is one, two, three, four, five. Costs are three, four, five, one, two. Start at station three: four in, one out, three in the tank. Plus three: six. Then the road takes two, two and two, and you roll home with zero. The answer is three.
The simple way tries every start. Stations zero, one and two each run dry on the first road. Four makes two roads, then runs dry. That's n starts, up to n roads each: n squared time.
Two ideas make it one pass. First, the totals. If the total gas is less than the total cost, no start works. Gas two, three, four, costs three, four, three: nine gas for ten cost, so minus one.
Second: say you start somewhere and run dry. You reached every station on the way with gas to spare. Starting at one of them empty can only be worse, so skip them all and start right after the dry spot.
In code, check the totals first. Then keep a start and a tank. At each station, add gas minus cost. If the tank drops below zero, move the start to the next station with an empty tank. At the end, the start is the answer.
Back to the example. Station zero: minus two, dry, so start at one. Minus two: start at two. Minus two: start at three. Then plus three, plus three: six in the tank. The answer is three, and that six pays for the roads we skipped: four, two, zero, home.
One pass over the stations, so the time is O of n. Just a start and a tank: O of one space.
Check the totals, reset when you run dry, never look back. That's Gas Station.