Gas Station
Find the lowest start that completes the loop, or -1
DSA, Medium, Greedy
Which structure or algorithm, and what does it cost.
A car drives around a ring road with gas stations numbered from 0. At station i you can fill up with gas[i] litres. The drive from station i to the next station uses cost[i] litres, and the last station links back to station 0. The tank starts empty and has no size limit. Return the lowest station number where you can start and drive the full loop back to it without running out. If no station works, return -1.
Examples
Constraints
- 1 <= number of stations <= 100,000, and
gasandcosthave the same length. - Each value is a whole number between 0 and 500,000.
Your answer must contain
- The simple method and why it is too slow; the best method and why it is correct; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n) time and O(1) extra memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Compare the total gas on the whole ring with the total cost. What does that tell you before you try any start?
Hint 2 the approach
Drive from a start and watch the tank. When it first goes negative, what does that tell you about the stations you passed?
Hint 3 the key step
If the drive fails after station i, no station from the start up to i can start the loop. Move the start past i and empty the tank.
Walkthrough
Full walkthrough brute force to best
Brute force
Try every station as the start. Simulate the whole loop: add the gas, pay the cost, and stop at the first failure. The first start that finishes is the answer. One simulation takes up to n steps, so this is O(n^2) time and O(1) memory. With 100,000 stations that is up to 10 billion steps, too slow.
Best method
Two facts. First, if the total gas is smaller than the total cost, no start works, so return -1. Second, drive from a candidate start and track the tank. If the drive first fails at station i, every station s between the start and i is also bad: you reached s with a tank of at least 0, so starting at s with an empty tank leaves you with no more tank at i than the real drive had, and that was negative. So move the start to i + 1 and reset the tank. When the total gas covers the total cost, the last candidate works. It is the station just after the lowest point of the running total around the ring, so driving from it never dips below the level it started at, and the spare gas covers the wrap-around. Every skipped station was proven bad, so this is also the lowest valid start.
Hand trace
Run on gas [3, 2, 5, 1, 4] and cost [4, 3, 2, 3, 2]. The total gas is 15 and the total cost is 14, so a start may exist. Start 0, tank 0. Station 0: gas minus cost is -1, the tank fails, so start becomes 1 and the tank resets. Station 1: -1, it fails, so start becomes 2. Station 2: +3, tank 3. Station 3: -2, tank 1. Station 4: +2, tank 3. There is no more failure, so the answer is 2.
Code
def start_station(gas, cost):
if sum(gas) < sum(cost):
return -1 # the loop can never be paid for
start = 0
tank = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0: # no station up to i can start the loop
start = i + 1
tank = 0
return startTime and memory
O(n) time, for the two sums and the single pass. O(1) memory, for a few numbers.
Common mistakes
- Skipping the total check. With too little gas in total there is no start, even if the single pass never fails near the end.
- Moving the start to station i instead of i + 1. The drive after station i is the one that failed, so station i itself is bad.
- Using "the start ran past the last station" as the -1 test instead of the total. Example 2 then returns 1.