PracticeNeetCode ↗LeetCode ↗
There are n gas stations arranged in a circle. gas[i] is the fuel available at station i, and cost[i] is the fuel needed to drive from station i to station i + 1. Return the starting station index that lets you complete the full circuit without running out of fuel, or -1 if it's impossible. A solution, if one exists, is unique.
sum(gas) < sum(cost), return -1 immediately.total = 0 (running tank) and start = 0 (candidate answer).i: total += gas[i] - cost[i].total < 0, set start = i + 1 and reset total = 0.start once the loop completes.Time: O(n) — Space: O(1)
def canCompleteCircuit(gas: list[int], cost: list[int]) -> int:
if sum(gas) < sum(cost):
return -1
total = 0
start = 0
for i in range(len(gas)):
total += gas[i] - cost[i]
if total < 0:
start = i + 1
total = 0
return startHow the solution above works, piece by piece.
start, adding gas[i] − cost[i] to the tank.i, no station from start to i can be the answer: each of them would arrive at i with even less fuel. So jump start to i + 1 and reset.start survives to the end is the answer; the total check guarantees the wrap-around part works.Running it on gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]:
gas − cost at each station. The tank goes negative at stations 0, 1 and 2, ruling them out. Starting at 3 the running sum stays ≥ 0.