Gas stations sit on a loop road, numbered 0 to n − 1 in driving order. Station i lets you fill up gas[i] units, and driving from station i on to the next one burns cost[i] units. After the last station the road leads back to station 0.
Your car's tank has no limit but starts empty. Pick a station to start from, drive once all the way around back to it, and never let the tank go below 0. Return the index of the station that makes this possible, or −1 if none does. When a start exists, there is only one.
Example 1
Input: gas = [2, 5, 1, 3], cost = [4, 1, 3, 2] Output: 1 Why: from 1 the tank reads 4, 2, 3, 1 after each leg; never below 0
2 more examples and the constraints
Example 2
Input: gas = [1, 2, 3], cost = [2, 2, 3] Output: -1 Why: 6 units of gas in all, but the loop burns 7
Example 3
Input: gas = [4], cost = [3] Output: 0 Why: one station; 4 units cover the 3 needed to come back
Constraints
- 1 ≤ n ≤ 100,000, and gas and cost both have length n
- 0 ≤ gas[i], cost[i] ≤ 10,000
- At most one starting station works
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every startO(n²)
- One pass, reset on emptyO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 stations | Verdict |
|---|---|---|---|
| Try every start | O(n²) | Mention it, then move on | |
| One pass, reset on empty | O(n) | Best; one pass, done |
n = number of stations.
Edge cases to test
- Not enough gas overall. [1, 2, 3] against [2, 2, 3]: total gas 6 < 7, so −1 no matter where you start.
- One station. [4] against [3] gives 0; [1] against [2] gives −1.
- Exactly enough. Total gas equal to total cost still works; the tank can end at exactly 0.
- Start at the last station. The answer can be n − 1, with the route wrapping back past station 0.
- Free legs. gas[i] = cost[i] = 0 is allowed and changes nothing.
Common mistakes
- Restarting at start + 1 instead of i + 1 after running dry, which brings back the O(n²) work.
- Returning start without checking total ≥ 0, so a loop with too little gas returns an index.
- Testing tank ≤ 0 instead of tank < 0, which throws away a start that arrives with exactly 0.
How to talk through it
- 1Clarify. Is the route a loop? Does the tank start empty? Is the answer unique if it exists?
- 2Give the brute force. Simulate from every start: O(n²), too slow for 100,000 stations.
- 3State the two facts. Enough total gas means a start exists. Running dry at i rules out every start up to i.
- 4Code the one pass. Keep total and tank; reset start and tank when the tank goes negative.
- 5Test out loud. Run a too-little-gas case and a start at the last station before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?