sagelearnai

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]   →  4

Hints

  1. If total gas < total cost, no start can work.
  2. If you start at s and run out before reaching j, then no station between s and j can be a valid start either.
  3. So after a failure at j, try starting at j + 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 -1
JavaScript 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;
}