Problem Statement

Gas Station

Picture a circular road with n gas stations on it. At each station you can pick up some gas: station i gives you gas[i] units. Driving from station i to the next station burns cost[i] units of gas. Your car's tank is empty when you start, and the tank can hold as much as you want. The question is: which station should you start at so you can drive all the way around the loop and get back to where you began? Return that starting station's index, or return -1 if no starting point works. The problem promises that if an answer exists, there is exactly one. The key idea is simple: if the total gas you can collect over the whole loop is at least the total gas you will burn, then some starting point works. So we just have to find it.

mediumGreedyArrayGreedyTime: O(n) · Space: O(1)

Signals to notice

circular route with gas stationsfuel gain vs costfind valid starting point

Brute force first

Try starting from each station, simulate the journey. Each start simulates the full circuit. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Single pass: track totalTank and currentTank. If currentTank goes negative, the start must be AFTER this point. Reset currentTank and move start to the next station. If totalTank ≥ 0 at the end, the last start position is valid. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Trace it on gas=[1,2,3,4,5], cost=[3,4,5,1,2]

precheck: sum(gas)=15 >= sum(cost)=15 -> solution exists; tank=0, start=0
i=0: tank += 1-3 = -2 -> tank<0, reset start=1, tank=0
i=1: tank += 2-4 = -2 -> tank<0, reset start=2, tank=0
i=2: tank += 3-5 = -2 -> tank<0, reset start=3, tank=0
i=3: tank += 4-1 = 3 -> tank>=0, keep start=3
i=4: tank += 5-2 = 6 -> tank>=0, keep start=3
return start=3

What must stay true

If the total gas ≥ total cost, a solution exists. If you run out of gas at station i starting from station s, then NO station between s and i can be the start — they'd all run out even sooner. So start from i+1. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Shape of the loop

if sum(gas) < sum(cost): return -1
tank = 0; start = 0
for i in 0..n-1:
    tank += gas[i] - cost[i]
    if tank < 0: start = i+1; tank = 0
return start

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Not understanding why skipping to i+1 is safe — if you can't reach i from s, any station between s and i would have less accumulated fuel at i, so they'd fail too. The fix is usually to return to the meaning of each move, not just the steps themselves.

Greedy Pattern