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]cost[i]
Example 1
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
Output: -1
Explanation: the stations hold 9 units of gas in all, but the three roads cost 10.
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.
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
- First, set up three numbers:
, the gain over the whole loop,total , the gas since the current start, andtank , the candidate station, which begins at 0.start - A single loop moves
over the stations. For each one, work outi and add it to bothgain = gas[i] - cost[i] andtotal .tank - If
is below zero, the car cannot get fromtank to stationstart . Seti + 1 tostart andi + 1 back to 0.tank - After the loop, return
ifstart is 0 or more, and -1 otherwise.total
The main
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:
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]cost = [2, 2]>=
The fourth line, 2, comes from gas = [1, 1, 4]cost = [2, 2, 1]
What if the code set start = ii + 1
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 andstart are the only values kept, however many stations the route has.gain
Dropping a running sum as soon as it goes below zero is also the move behind