Gas Station

MediumGreedy · Prefix Sum🧩 GreedyLeetCode #134 ↗Updated

Problem

Stations 0..n-1 sit on a circular road. At station i you may fill up gas[i] units, and driving on to station i+1 burns cost[i] units. Starting with an empty tank, return the station from which you can drive one full lap clockwise, or -1 if none exists (the answer is unique when it exists).
Inputgas=[1,2,3,4,5] cost=[3,4,5,1,2]Output3
Inputgas=[2,3,4] cost=[3,4,3]Output-1

1 ≤ n ≤ 105  ·  0 ≤ gas[i], cost[i] ≤ 104  ·  answer is unique if it exists

Try it yourself

Java
class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
If the tank first goes negative at station j when starting from s, then no station between s and j can start either (each arrives there with ≥ 0 fuel, which only helps). And a lap is possible iff Σgas ≥ Σcost.
PatternGreedy

Instinct An optimisation where one obvious local rule (earliest end, farthest reach, biggest first) never needs undoing - commit to it, then try hard to break it.

Memory hack Grab the best bite now and never look back - but only once a counterexample hunt fails to make you regret it.

Open the Greedy guide →

Approaches

Brute ForceSimulate from Every Station

Time O(n2)Space O(1)

Try each start and drive n legs, adding gas[i] - cost[i] to the tank; abandon the start as soon as the tank drops below zero. The first start that survives all legs is the answer.

Java
public int canCompleteCircuit(int[] gas, int[] cost) {
    int n = gas.length;
    for (int start = 0; start < n; start++) {
        int tank = 0, legs = 0;
        while (legs < n) {
            int i = (start + legs) % n;
            tank += gas[i] - cost[i];
            if (tank < 0) break;
            legs++;
        }
        if (legs == n) return start;
    }
    return -1;
}

Direct translation of the statement, but quadratic for n = 105.

At a glance

LevelApproachTimeSpace
Brute ForceSimulate from Every StationO(n2)O(1)
BetterSimulation with Skip-AheadO(n)O(1)
OptimalOne-Pass Greedy (Total + Running Surplus)O(n)O(1)
Common pitfalls
  • Resetting start = i instead of i + 1 — station i itself just failed.
  • Skipping the total ≥ 0 check — returns a start even when no lap is possible.
  • Forgetting the wrap-around (% n) in the simulation versions.
Interview tips
  • Prove both lemmas aloud: the skip-ahead argument and the total-sum feasibility test.
  • Work with diff[i] = gas[i] - cost[i]; the problem becomes a prefix-sum one.
  • Mention that the unique-answer guarantee is why the first surviving start is enough.
Pattern
Greedy reset on negative running sum → find a start where every prefix of a circular sequence stays ≥ 0.
My notes saved in this browser