LeetCode #134 Medium

Gas Station

Find a starting station that permits one complete clockwise circuit, or return -1.

arraygreedysimulation
Open on LeetCode ↗
02

Intuition

Simulating a full trip from every station is quadratic. A circuit is possible only when total gas covers total cost. During one scan, if the running tank becomes negative at station i, no station between the current candidate and i can succeed because each would begin with an even smaller accumulated prefix. Therefore the next station is the only remaining candidate after that failure.

How to spot this pattern

A circular route with gains and costs often reduces to global feasibility plus a greedy reset. When a negative prefix proves every start within that prefix fails, one linear scan is sufficient.

03

Approach

1

Track global fuel feasibility

Add every gas[i] - cost[i] to total. If the final total is negative, the route consumes more fuel than exists and no starting point can work.

2

Test one candidate with a running tank

Accumulate the same net gain in tank from the current candidate. As long as it stays nonnegative, that candidate can reach the next station.

3

Discard an entire failed prefix

When tank drops below zero at i, set the candidate to i + 1 and reset the tank. The failed accumulated segment cannot contain a valid start, so no candidate inside it needs separate simulation.

04

Solution

1class Solution:
2 def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
3 total = 0
4 tank = 0
5 start = 0
6 for i in range(len(gas)):
7 gain = gas[i] - cost[i]
8 total += gain
9 tank += gain
10 if tank < 0:
11 start = i + 1
12 tank = 0
13 return start if total >= 0 else -1
05

Common pitfalls

Returning a candidate without checking total fuel

✗ Wrong
return start
✓ Right
return start if total >= 0 else -1

A locally viable suffix cannot compensate when the complete circuit has a net deficit.

Restarting at the failing station

✗ Wrong
start = i
✓ Right
start = i + 1

The tank is already negative after processing station i, so i cannot be the new start for the next edge.

Resetting only on zero

✗ Wrong
if tank == 0:
✓ Right
if tank < 0:

A zero tank is valid when arriving exactly empty; only a negative balance proves failure.

06

Edge cases

Total gas is smaller than total cost

Return -1 regardless of local surpluses.

One station with enough gas

The running tank remains nonnegative and index zero is returned.

The valid start is after several deficits

Each negative running balance advances the candidate beyond the entire failed segment.

07

Complexity

Time
O(n)
Space
O(1)
Each station is processed once with constant bookkeeping.