Gas Station

Find the station from which a car with an empty tank can drive once around a circular route.

A circular route has n gas stations, numbered 0 to n - 1. Station i holds gas[i] units of gas, and the road from station i to the next station uses cost[i] units. The road from the last station leads back to station 0. A car with an unlimited tank starts empty at one of the stations, takes the gas there and drives on. Return the index of the station from which the car can drive once around the whole route, or -1 if no station works. If an answer exists, it is unique.

Example 1
Input: gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]
Output: 3
Explanation: starting at station 3 with 4 units, the car reaches station 4 with 3 units left, station 0 with 6, station 1 with 4, station 2 with 2 and station 3 again with 0.
Example 2
Input: gas = [2, 3, 4], cost = [3, 4, 3]
Output: -1
Explanation: the stations hold 9 units of gas in all, but the three roads cost 10.
Solution

The Idea

Picture a ring road with five filling stations and a car with an empty tank. At each station the car takes all the gas there, then drives to the next station, and the road burns some of it. The trip succeeds if the car gets all the way round to the station where it began.

Try Example 1 by hand. Starting at station 0, the car takes 1 unit, but the road to station 1 costs 3, so it stops on the way. Station 1 fails the same way, with 2 units against a road of 4. Starting at station 3, the car takes 4 units and the road costs 1, so it reaches station 4 with 3 units. Going on, it arrives at station 0 with 6, then 4, then 2, and back at station 3 with exactly 0.

Trying every station like this repeats a lot of driving. Each attempt can cover up to n roads, so n attempts take about n2 steps. Two questions come up. Can one failed attempt tell us something about other stations? And can we tell quickly when no station works, as in Example 2?

For both, what matters at a station is not its gas alone but its gas minus the cost of the road leaving it. Call that the station's gain: it says how much the tank goes up or down from arriving at the station to arriving at the next one. Look at the picture below.

Example 1 drawn as five stations in a row with the roads between them and an arc from station 4 back to station 0. The gains are -2, -2, -2, +3 and +3. The tank goes below zero after stations 0, 1 and 2, so the next start moves to 1, 2 and 3. From station 3 the tank reads 3 and then 6. The total gain is 0, so the loop can be done from station 3.

Each box is a station with its gas, and each arrow is a road with its cost. The arc on top is the road from station 4 back to station 0. The row labelled gain holds gas minus cost: -2 for each of stations 0, 1 and 2, and +3 for stations 3 and 4.

Now drive once from left to right and keep a running tank. Starting at station 0, the tank after the road is -2, so station 0 fails. Here is the key point. Suppose a drive from some start fails on the road after station i. Then every station between that start and i fails too. The car reached each of them with a tank of 0 or more, and arriving with something can only help, so starting there with an empty tank does no better.

So after a failure, the next start is the station after i, and the tank goes back to 0. That is what the rows labelled tank after the road and next start show: -2 → 0 three times, with the next start moving to 1, 2 and then 3. From station 3 the tank reads 3, then 6, and stays at 0 or above to the end of the row.

Moving the start straight past a stretch that failed, using only what this one drive showed, and never going back to retry a skipped station, is called a greedy choice. It turns n attempts into a single drive along the row.

But the drive ended at station 4. Station 3 still has to cover the roads after stations 0, 1 and 2, which made the earlier starts fail. Add up all the gains: -2 - 2 - 2 + 3 + 3 = 0. The car leaves station 4 with 6 units, and the three failed stations lose 2 each, so it arrives back at station 3 with 6 - 6 = 0. That matches the 4, 2 and 0 in Example 1.

This works whenever the total gain is 0 or more. The 6 units are the total gain minus what the failed stretches lost, so they always cover those losses. Inside each failed stretch, the tank sank below where it began only on that stretch's last road, so the car never runs dry before it is back at the start. And in Example 2 the total gain is 9 - 10 = -1: the roads need more gas than all the stations hold, so no start can work.

Solution Approach

The slow way tries every start; the faster way settles three things: what to keep track of during one drive, where the next start goes after a failure, and how to decide at the end.

Trying every start

Why not simply drive the loop from each station? That needs two loops, one inside the other: the first picks a start, and the second drives up to n roads from it, stopping when the tank goes below zero. It is correct, but it takes about n2 steps, and most of them repeat a drive over roads already known to fail.

What to keep track of

What does the single drive need to remember? Two running sums. The tank holds the gains since the current start, and it decides when a start fails. The total holds the gains of every station, whatever the start, and it decides at the end whether any start works.

Where the next start goes

When the tank drops below zero after station i, why the station after i and not station i itself? Just before station i the tank was 0 or more, and adding station i's gain pushed it below zero. So that gain is negative, and a car starting at station i with an empty tank fails on its very first road.

Deciding at the end

Once the drive has passed the last station, is a second lap needed to check the start? No. If the total is 0 or more, the tank left over covers every failed stretch, as the 6 units did in Example 1, so the last start is the answer. If the total is below zero, no start works. Arriving back with an empty tank still counts, so the check is total >= 0.

Java Solution

The method canCompleteCircuit works in these steps:

  1. First, set up three numbers: total, the gain over the whole loop, tank, the gas since the current start, and start, the candidate station, which begins at 0.
  2. A single loop moves i over the stations. For each one, work out gain = gas[i] - cost[i] and add it to both total and tank.
  3. If tank is below zero, the car cannot get from start to station i + 1. Set start to i + 1 and tank back to 0.
  4. After the loop, return start if total is 0 or more, and -1 otherwise.

The main method runs both examples, a loop with exactly enough gas, a loop whose answer is the last station, and two loops with a single station, one with enough gas and one without.

Java
public class GasStation {

    public static int canCompleteCircuit(int[] gas, int[] cost) {
        int total = 0;    // gas minus cost over the whole loop
        int tank = 0;     // fuel since the current start
        int start = 0;
        for (int i = 0; i < gas.length; i++) {
            int gain = gas[i] - cost[i];
            total += gain;
            tank += gain;
            if (tank < 0) {          // cannot reach station i + 1 from start
                start = i + 1;       // so no station from start to i works
                tank = 0;
            }
        }
        return total >= 0 ? start : -1;
    }

    public static void main(String[] args) {
        System.out.println(canCompleteCircuit(new int[] {1, 2, 3, 4, 5},
                                              new int[] {3, 4, 5, 1, 2}));
        System.out.println(canCompleteCircuit(new int[] {2, 3, 4}, new int[] {3, 4, 3}));
        System.out.println(canCompleteCircuit(new int[] {3, 1}, new int[] {2, 2}));
        System.out.println(canCompleteCircuit(new int[] {1, 1, 4}, new int[] {2, 2, 1}));
        System.out.println(canCompleteCircuit(new int[] {5}, new int[] {4}));
        System.out.println(canCompleteCircuit(new int[] {1}, new int[] {2}));
    }
}

Running it prints:

Output
3
-1
0
2
0
-1

The 3 and -1 at the top match Examples 1 and 2. Look at the third line, 0. With gas = [3, 1] and cost = [2, 2], station 0 gains 1 and station 1 loses 1, so the car gets back to station 0 with an empty tank. The total is exactly 0, and the >= check accepts it.

The fourth line, 2, comes from gas = [1, 1, 4] and cost = [2, 2, 1]. Stations 0 and 1 each lose 1, so the start moves twice and lands on the last station, whose gain of 3 covers both losses. The last two lines have a single station, whose road leads back to itself: 5 units against a cost of 4 gives 0, and 1 unit against a cost of 2 gives -1.

What if the code set start = i after a failure, instead of i + 1? Run on Example 1, that version returns 2, not 3. Station 2 is where the tank went below zero, and its gain of -2 stops a car starting there on its first road.

Complexity

The method drives along the stations once and keeps a few numbers.

  • Time: O(n), because the single loop looks at each of the n stations once, and a station passed over by a failed stretch is never tried again.
  • Space: O(1), because total, tank, start and gain are the only values kept, however many stations the route has.

Dropping a running sum as soon as it goes below zero is also the move behind Maximum Subarray, which looks for the largest sum of neighbouring numbers in an array.