medium +25 pts

Gas Station Circuit

Find the only gas station that can complete a circular route, or return -1.

There are n gas stations along a circular route, numbered 0 to n-1. You have two lists of equal length: - `gas[i]` is the amount of gas you can refill at station i. - `cost[i]` is the amount of gas needed to travel from station i to the next station (i+1) % n. You begin with an empty tank (tank = 0) and must choose exactly one starting station. At each station, you fill up `gas[i]` (tank += gas[i]) and then travel to the next station (tank -= cost[i]). You can only move forward (in increasing index order, wrapping around). If your tank would ever go negative, that start fails. Implement the function `can_complete_circuit(gas, cost)` that returns the **smallest** starting index that allows you to complete the full circuit, or **-1** if no such start exists. It is guaranteed that *if a solution exists, it is unique* (so the minimum is the only one). Constraints: - 1 <= len(gas) == len(cost) <= 10^5 - 0 <= gas[i], cost[i] <= 10^4 - Your solution must run in O(n) time and O(1) extra space.

Constraints

1 <= len(gas) <= 10^5, len(cost) == len(gas), 0 <= gas[i], cost[i] <= 10^4. Expected O(n) time, O(1) space.

Example

>>> can_complete_circuit([1,2,3,4,5], [3,4,5,1,2])
3
>>> can_complete_circuit([2,3,4], [3,4,3])
-1
>>> can_complete_circuit([4], [3])
0
>>> can_complete_circuit([1,2], [2,1])
1
25 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

If total gas is less than total cost, no solution exists.
Track the current segment's tank; when it becomes negative, reset and move the candidate start to the next station.
Once you finish one pass, the candidate start (if total gas >= total cost) is the answer.
Use a single variable for the running tank and one for the total surplus.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.