Full answer
Problem
There are n stations in a circle. Station i gives gas[i] and driving from i to i + 1 costs cost[i]. The tank starts empty. Return the index of a station from which you can complete the loop once, or -1 if impossible. If a solution exists, return the smallest valid index.
Example: gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2] returns 3. gas = [2, 3, 4], cost = [3, 4, 3] returns -1.
Constraints: 1 <= n <= 10^5; values from 0 to 10^4.
Brute force
Simulate from every start and stop when the tank goes negative: O(n^2).
Optimal approach
- If
sum(gas) < sum(cost), return -1. start = 0,tank = 0. For each i:tank += gas[i] - cost[i]; iftank < 0, setstart = i + 1,tank = 0.- Return
start.
Why it works
Skipping claim: if starting at s the tank first goes negative after station i, then no station k between s and i can be a start. Arriving at k from s, the tank was non-negative, so starting at k with an empty tank leaves you with no more fuel at every later point than the run from s had, and that run failed at i.
Existence claim: when total gas is at least total cost, the final start works. The segment from start to the end of the array keeps a non-negative tank by construction, and the deficit of the earlier part is covered by the surplus, because the total over the whole circle is non-negative. The cross-check confirms the result equals the first valid start found by simulation.
Complexity
O(n) time and O(1) space.
Code
import random
def can_complete_circuit(gas, cost):
"""Start index for one full clockwise loop, or -1. One pass, O(n), O(1).
If the tank goes negative between start and i, no station in that range can be the start."""
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 start
def brute(gas, cost):
n = len(gas)
for s in range(n):
tank, ok = 0, True
for k in range(n):
i = (s + k) % n
tank += gas[i] - cost[i]
if tank < 0:
ok = False
break
if ok:
return s
return -1
if __name__ == "__main__":
assert can_complete_circuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]) == 3
assert can_complete_circuit([2, 3, 4], [3, 4, 3]) == -1
assert can_complete_circuit([5], [5]) == 0
rng = random.Random(94)
for _ in range(2000):
n = rng.randint(1, 8)
g = [rng.randint(0, 6) for _ in range(n)]
c = [rng.randint(0, 6) for _ in range(n)]
b = brute(g, c)
got = can_complete_circuit(g, c)
assert (got == -1) == (b == -1)
if got != -1:
assert brute(g[got:] + g[:got], c[got:] + c[:got]) == 0 # the returned start works
assert got == b # and it is the first valid start
print("all tests passed")Save as b94_gas_station.py and run python3 b94_gas_station.py. It prints all tests passed (Python 3.13.5).
Edge cases
Single station (valid if gas >= cost). Total exactly equal to cost (valid start exists). All stations with zero net. Many valid starts (this method returns the smallest).
Pattern
Greedy restart with a running sum, closely related to Kadane's algorithm and minimum prefix sums: the answer is the index right after the lowest point of the prefix sum of gas - cost. Similar ideas appear in circular subarray problems and in rebalancing tours.
import random
def can_complete_circuit(gas, cost):
"""Start index for one full clockwise loop, or -1. One pass, O(n), O(1).
If the tank goes negative between start and i, no station in that range can be the start."""
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 start
def brute(gas, cost):
n = len(gas)
for s in range(n):
tank, ok = 0, True
for k in range(n):
i = (s + k) % n
tank += gas[i] - cost[i]
if tank < 0:
ok = False
break
if ok:
return s
return -1
if __name__ == "__main__":
assert can_complete_circuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]) == 3
assert can_complete_circuit([2, 3, 4], [3, 4, 3]) == -1
assert can_complete_circuit([5], [5]) == 0
rng = random.Random(94)
for _ in range(2000):
n = rng.randint(1, 8)
g = [rng.randint(0, 6) for _ in range(n)]
c = [rng.randint(0, 6) for _ in range(n)]
b = brute(g, c)
got = can_complete_circuit(g, c)
assert (got == -1) == (b == -1)
if got != -1:
assert brute(g[got:] + g[:got], c[got:] + c[:got]) == 0 # the returned start works
assert got == b # and it is the first valid start
print("all tests passed")Total check plus one pass with restarts, cross-checked against full simulation from every start, including that the returned start is the first valid one.
Complexity
Time: O(n). Space: O(1). Equivalent to choosing the index after the minimum prefix sum of gas - cost.
By level
Fresher: Simulates from one start and then explains why a failure at i rules out every station in between. Writes the one-pass version with the total check.
Mid: Argues both the skipping and existence claims and relates them to minimum prefix sums. Handles multiple valid starts.
Senior: Generalizes to tank capacity limits and circular route planning, and discusses when greedy restarts stop working. Connects the prefix-sum view to circular buffer and balancing problems.
Key points
- Total gas < total cost means -1
- Restart after any station where the tank goes negative
- Skipped stations cannot be starts
- The last restart is the answer
- One pass, O(n) time and O(1) space
Common mistakes
- Simulating from every start (O(n^2))
- Forgetting the total check
- Resetting start to i instead of i + 1
- Assuming the answer is unique
Follow-ups
- How would you find all valid starts?
- What if the tank has a maximum capacity?
- How is this related to minimum prefix sums?
Tips
- Prove the skipping claim in words
- State the total condition first
- Mention the prefix-sum view
Evaluation rubric
- Correct algorithm
- Correctness argument
- Handles impossibility
- Correct complexity