SDE & MLE Prep

134. Gas Station

Problem

Gas stations stand on a circular route; station i has gas[i] fuel, and driving from it to station i + 1 costs cost[i]. Starting with an empty tank, return the station from which you can drive around the whole circuit once, or −1 if none works. The answer is unique when it exists.

Example: gas = [1,2,3,4,5], cost = [3,4,5,1,2] → 3

Constraints: n ≤ 10⁵.

If total gas < total cost → impossible. Otherwise, scan with a running tank; whenever it drops below 0, no station in the current segment can be the start → restart from i + 1.

Complexity: O(n).

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(gas) < sum(cost):
            return -1
        start = tank = 0
        for i, (g, c) in enumerate(zip(gas, cost)):
            tank += g - c
            if tank < 0:
                start, tank = i + 1, 0
        return start