Skip to content

Gas Station

Find the one station from which you can drive round a circular road without running out of fuel.

MediumGreedy
Solve on LeetCode

The problem

Stations sit on a circular road. At station i you fill up gas[i] units of fuel, and driving from it to the next station burns cost[i] units. Starting with an empty tank, return the index of the station from which you can drive all the way round once, or -1 if there is none. You can assume that when an answer exists, it is unique.

Input gas = [4, 1, 5, 2], cost = [3, 4, 2, 3]

Output 2

Starting at station 2, the tank holds 3, then 2, then 3, then 0 when you arrive back at station 2.

Input gas = [1, 2, 2], cost = [2, 2, 2]

Output -1

The stations hold 5 units in total, but the trip needs 6, so no start works.

Key constraint: There can be 100,000 stations, so simulating the trip from every start, O(n^2), is too slow.

How to spot the pattern

  • A circular route where you gain and lose a resource at each stop.
  • You need a starting point from which a running total never goes negative.

The idea

If the total gas is less than the total cost, no start works. Otherwise drive from a candidate start and track the tank: if it goes negative right after station i, then no station from the start to i can work either, because each of them would reach station i with no more fuel than you had. So skip them all and try i + 1 with an empty tank; the candidate left at the end is the answer.

Brute force: Simulate the full trip from every station, which takes O(n^2) time.

Step by step

  1. 1If the sum of gas is less than the sum of cost, return -1.
  2. 2Set start = 0 and tank = 0.
  3. 3For each station i, add gas[i] - cost[i] to tank.
  4. 4If tank drops below 0, set start = i + 1 and reset tank to 0.
  5. 5Return start.

See the pattern move

The greedy pattern on a small example. Step through it, or press play.

Code

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(gas) < sum(cost):
            return -1  # not enough fuel in total, whatever the start
        start, tank = 0, 0
        for i in range(len(gas)):
            tank += gas[i] - cost[i]
            if tank < 0:
                # starting anywhere from `start` to i runs dry here too, so try i + 1
                start, tank = i + 1, 0
        return start

Complexity

Time

O(n)

Space

O(1)

One pass over the stations.

Watch out for

  • Retrying at start + 1 after a failure: every station up to i fails as well, so jump straight to i + 1.
  • Skipping the total check: the pass always ends with some start, even when no start works.

Follow-up questions

Why is enough total fuel also enough for some start?

Picture the running total of gas[i] - cost[i] around the circle. If you start right after the point where it is lowest, every partial sum of your trip is at least 0, so the tank never runs dry.

What if several starts could work?

The same pass still returns one valid start; it is just one of several answers.

In Hinglish

Total gas kam hai toh seedha -1. Warna jahan tank negative hua, uske pehle ke saare stations bekaar hain, agle station se naya start karo.

Related problems