Gas Station
Difficulty: Medium · Pattern: Greedy · LeetCode #134
n gas stations sit on a circular route. Station i gives gas[i] units of fuel, and driving from station i to i + 1 costs cost[i]. Starting with an empty tank at some station, you want to travel around the circle once. Return the starting station index if possible, else −1. The answer is unique if it exists.
Examples
text
gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2] → 3
gas = [2, 3, 4], cost = [3, 4, 3] → −1
gas = [5, 1, 2, 3, 4], cost = [4, 4, 1, 5, 1] → 4Hints
- If total gas < total cost, no start can work.
- If you start at
sand run out before reachingj, then no station betweensandjcan be a valid start either. - So after a failure at
j, try starting atj + 1.
Approach
Track total (sum of gas − cost over all stations) and tank (running fuel since the current candidate start). When tank goes negative at station i, reset start = i + 1 and tank = 0. Any station between the old start and i would arrive at i with even less fuel, since it skips a non-negative prefix. At the end, return start if total ≥ 0, else −1. One pass.
Complexity
Time: O(n). Space: O(1).
Python solution
def canCompleteCircuit(gas, cost):
total = tank = start = 0
for i in range(len(gas)):
diff = gas[i] - cost[i]
total += diff
tank += diff
if tank < 0:
start, tank = i + 1, 0
return start if total >= 0 else -1JavaScript solution
function canCompleteCircuit(gas, cost) {
let total = 0, tank = 0, start = 0;
for (let i = 0; i < gas.length; i++) {
const d = gas[i] - cost[i];
total += d; tank += d;
if (tank < 0) { start = i + 1; tank = 0; }
}
return total >= 0 ? start : -1;
}