Gas Station
Problem
There are n gas stations arranged in a circle. Station i offers gas[i] units of fuel, and driving from station i to station i + 1 (wrapping around from the last station to the first) consumes cost[i] units. You begin with an empty tank at a station of your choosing and must complete one full lap, visiting every station once in order. Return the index of a station from which the lap can be completed, or -1 if no such station exists. If several stations would work, any one of them is accepted.
- Between 1 and 200,000 stations.
- Every
gas[i]andcost[i]is a non-negative integer no larger than 100,000.
Examples
gas = [2, 1, 8, 9, 8], cost = [4, 8, 5, 3, 7]→2. The per-station surplus is[-2, -7, 3, 6, 1]. Leaving station 2 the tank reads 3, 9, 10, 8, 1 after each leg and never goes negative; leaving station 0 or 1 you are short on the very first leg, and leaving 3 or 4 you run dry on the way to station 2.gas = [4, 2, 7], cost = [5, 3, 6]→-1. Total gas 13 is less than total cost 14, so no start can work.gas = [6], cost = [6]→0. One station; you just needgas[0] >= cost[0].
Hints
- If the total gas is less than the total cost, is any start possible? And if it is not less?
- Suppose you start at
sand run dry just before reaching stationf. Could any station strictly betweensandfbe a valid start? - One pass: track the running tank; whenever it goes negative, reset the tank and move the candidate start to the next station. The final candidate is the answer if the global total is non-negative.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.