Gas Station (LeetCode 134): Solution and Explanation

Medium
Array
Greedy

Stations sit on a circular route. Station i gives you gas[i] fuel and driving to the next station costs cost[i]. Starting with an empty tank, find the station from which you can drive the full loop once, or return -1 if no start works.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The obvious approach is to simulate from every station: start with an empty tank, walk around the circle, and stop as soon as the tank goes negative. That is O(n²), which is too slow for 100,000 stations, but it shows what matters. Each station contributes a net amount gas[i] - cost[i], and a start works only if the running sum of those net amounts never dips below zero during the loop.

The first observation handles feasibility. If the total gas is less than the total cost, no start can work, because the whole trip consumes more than it provides. The reverse is also true: if total gas is at least total cost, some start always exists. That is why the reference code checks sum(gas) < sum(cost) first and returns -1 immediately.

The second observation is what makes it linear. Suppose you start at station s and the tank first goes negative after station i. Any station between s and i would also fail before reaching i + 1. You arrived at each of those intermediate stations with a non-negative tank, so starting there fresh with zero fuel only leaves you with less gas by the time you get to i. That means you can skip all of them and try i + 1 as the next candidate.

Put together, a single pass is enough. Keep a running tank, reset it to zero and move the candidate start forward whenever it turns negative, and whatever candidate survives to the end is the answer, guaranteed by the total sum check.

Approach: Greedy single pass

  1. If sum(gas) < sum(cost), return -1 because no starting station can complete the circuit.
  2. Initialize total = 0 for the current tank and start = 0 for the candidate starting station.
  3. For each index i, add the net fuel gas[i] - cost[i] to total.
  4. If total drops below zero, the current candidate cannot reach station i + 1, and neither can any station between it and i. Reset total = 0 and set start = i + 1.
  5. After the loop, return start. The earlier total check guarantees this candidate can also cover the stations before it when it wraps around.

Step-by-step example

gas = [1,2,3,4,5], cost = [3,4,5,1,2]
  1. Total gas is 15 and total cost is 15, so a solution exists.
  2. i = 0: net is 1 - 3 = -2, so total = -2. It is negative, so reset total to 0 and set start = 1.
  3. i = 1: net is 2 - 4 = -2, total = -2. Reset again, start = 2.
  4. i = 2: net is 3 - 5 = -2, total = -2. Reset, start = 3.
  5. i = 3: net is 4 - 1 = 3, total = 3, still non-negative.
  6. i = 4: net is 5 - 2 = 3, total = 6. The loop ends and the function returns 3.

Code: Python, Java, C++

1class Solution:
2    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
3        if sum(gas) < sum(cost):
4            return -1
5            
6        total = 0
7        start = 0
8        for i in range(len(gas)):
9            total += gas[i] - cost[i]
10            if total < 0:
11                total = 0
12                start = i + 1
13        return start

Time and space complexity

Time

O(n)

Computing both sums takes one pass each, and the greedy loop visits every station once, so the total work is linear in the number of stations.

Space

O(1)

Only a few integer variables are used, regardless of how many stations there are.

Other approaches

Simulate from every start (time O(n²), space O(1))

For each station, drive around the loop and stop at the first negative tank. It is simple and obviously correct, which makes it useful for testing the greedy, but it repeats a lot of work and times out on large inputs.

Minimum prefix sum (time O(n), space O(1))

Compute the running sum of gas[i] - cost[i] and find the index where it reaches its minimum. The station right after that minimum is the answer when the total is non-negative. It is the same insight phrased in terms of prefix sums rather than resets.

Common mistakes

  • Setting start = i instead of i + 1 after a failure. Station i is where the tank went negative, so it cannot be the new start.
  • Forgetting the total gas versus total cost check. Without it, the loop always returns some index, even when no valid start exists.
  • Trying to verify the final candidate by simulating the wrap-around. It is unnecessary, since the total check already proves the remaining stations can be covered.
  • Resetting the tank to the current net value instead of zero, which carries the deficit into the next candidate's run.

Frequently asked questions

Why does total gas greater than or equal to total cost guarantee a solution?

The running sum of net fuel around the circle ends at a non-negative value. If you start right after the point where that running sum hits its minimum, every partial sum from there is at least zero, so the tank never runs dry.

Why can we skip all stations between the old start and the failure point?

You reached each of those stations with a non-negative tank. Starting at one of them with an empty tank leaves you with no more fuel than you had on the original run, so you would fail at the same station or earlier.

Is the answer unique?

The problem guarantees that if a solution exists it is unique, so returning the single surviving candidate is enough. The greedy pass finds that station directly.

What is the time complexity of the Gas Station greedy solution?

It runs in O(n) time with O(1) extra space. Each station is processed once in the main loop, plus the linear work to compute the two sums.