Gas Station – Solution & Complexity
Watch: Gas Station by skipping every station you passed
Trying every start and driving the whole loop is O(n²). Write each station as gas minus cost: +1, +2, −5, +4, −2. Start at 0 and the tank goes 1, 3, then −2, so you run out before station 3. Stations 1 and 2 can't be the start either: you reached them with gas in the tank and still failed, so starting there empty only does worse. Reset the tank to 0 and start at station 3: 4, then 2. If total gas minus total cost isn't negative (here it's 0), the last start is the answer: station 3. One pass, O(n) time, O(1) space.
Solution Walkthrough
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.
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.
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 andiis disqualified: they would inherit an even smaller tank by the time they reachi + 1. - So you can reset the candidate start to
i + 1and continue.
Step 4: Final solution (all languages)
One pass computes both the global feasibility check and the greedy candidate reset.
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.
Part of NeetCode 150 · LeetCode 150