← Whiteboard questions

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

Input gas = [3, 2, 5, 1, 4], cost = [4, 3, 2, 3, 2]
Output 2
Why from station 2 the tank after each drive is 3, 1, 3, 2, 1. Starting at station 0 or 1 fails on the first drive.
Input gas = [2, 2, 2], cost = [3, 2, 2]
Output -1
Why the loop costs 7 litres in total but the stations give only 6.
Input gas = [5], cost = [5]
Output 0
Why one station: the gas pays for the drive exactly, so the tank may reach 0.

Constraints

Your answer must contain

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 start

Time 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.

Related problems

More Greedy problems
Gas Station: hints, walkthrough and Python solution