What is Gas Station
There are n gas stations on a circle. gas[i] is the fuel you collect at station i. cost[i] is the fuel required to drive from station i to station i + 1. You start with an empty tank and may begin at one station. Return the starting index that completes one full circuit, or -1 when no station works. If a start exists, it is unique.
Example 1. Start at station 3. The tank stays non-negative all the way around: 3 to 4 to 0 to 1 to 2 and back to 3.
gas = 1 2 3 4 5 cost = 3 4 5 1 2 Output: 3
Example 2. Total gas is 9 and total cost is 10, so the circuit is impossible.
gas = 2 3 4 cost = 3 4 3 Output: -1
Approach
Interactive visualization
The walk starts on the first pseudocode line. Next and Play move one step at a time, and the highlighted line is the line that just ran.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each station is visited once. |
| Space | O(1) | Tank, total surplus, and the candidate start. |
| Greedy choice | Restart after a dip | A station inside a failed stretch cannot be the unique start. |
Implementation