Gas Station – Solution & Complexity

Solution Walkthrough

  1. Step 1: Check feasibility first

    • If the total gas is less than the total cost, no starting position can succeed.
    • If the total gas is enough, the answer exists and is unique in the standard problem statement.
  2. Step 2: Brute-force baseline

    • Try every index as a start and simulate the full circle.
    • That works, but it costs O(n^2) in the worst case.
  3. Step 3: Greedy reset insight

    • Scan the stations once while tracking the current tank from the current candidate start.
    • When the tank drops below zero at station i, every station between the candidate start and i is disqualified: they would inherit an even smaller tank by the time they reach i + 1.
    • So you can reset the candidate start to i + 1 and continue.
  4. Step 4: Final solution (all languages)

    One pass computes both the global feasibility check and the greedy candidate reset.

    def can_complete_circuit(gas: list[int], cost: list[int]) -> int:
        total = 0
        tank = 0
        start = 0
    
        for i in range(len(gas)):
            delta = gas[i] - cost[i]
            total += delta
            tank += delta
            if tank < 0:
                start = i + 1
                tank = 0
    
        return start if total >= 0 else -1
  5. Step 5: Common mistakes and follow-ups

    • Returning the last reset point without checking the total fuel balance first.
    • Resetting too early: only a negative running tank proves the current candidate cannot work.
    • Follow-up: if the route were not guaranteed to have a unique answer, you could still find one valid start with the same greedy scan.

FAQ