Gas Station

Gas Station feels like a road trip puzzle. There is a ring of stations around a track. Each one gives you some fuel and charges you some fuel to reach the next. You want one starting station from which you can drive the full loop. The slow way tries starting from every station. The fast way solves it in one pass. The leap there is the real test.

🎯 The Problem

You get two arrays of the same length and must find one valid starting station for the loop.

  • gas[i] is the fuel you pick up at station i.
  • cost[i] is the fuel needed to drive from station i to the next one.
  • The stations form a circle. After the last one you loop back to the first.
  • You start with an empty tank.
  • Return the index of a station you can begin from and drive all the way around once.
  • If no such station exists, return -1. The valid start is unique when it exists.

Let us say gas = [1, 2, 3, 4, 5] and cost = [3, 4, 5, 1, 2]. Starting at station 3 works. So the answer is 3.

Input: gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]
Output: 3
Explanation: Start at station 3. Tank fills and never drops below zero around the loop.

The key number at each station is the net fuel, which is gas[i] - cost[i]. If it is positive you gain fuel there. If it is negative you lose fuel. Here is the ring with the net at each station.

loop back

s0 net = -2

s1 net = -2

s2 net = -2

s3 net = +3

s4 net = +3

🐒 Approach 1: Try Every Start (Brute Force)

Pick each station as a possible start and simulate the full loop.

The idea:

  • Try station 0 first. Drive the whole circle and track the tank.
  • If the tank never drops below zero, that station is the answer.
  • If it drops below zero, try station 1, then 2, and so on.

How it works:

  • Outer loop picks the starting station.
  • Inner loop drives the loop from that start and adds each net.
  • Stop a start early the moment the tank goes negative.

Why it is weak:

  • For each start you may drive the whole loop again.
  • That is a loop inside a loop.
  • Time grows as O(nΒ²). Too slow on many stations.

Here is the try-every-start code:

gas_station_brute_force.py
def can_complete_circuit(gas, cost):
n = len(gas)
for start in range(n):
tank = 0
for step in range(n):
i = (start + step) % n
tank += gas[i] - cost[i]
if tank < 0:
break
else:
return start
return -1

⚑ Approach 2: One Pass With Total and Tank (Best)

The idea in one line: one sweep tells you both whether an answer exists and where it starts.

The idea:

  • The total of all nets says if the loop is possible at all.
  • The running tank says where a valid start begins.
  • A net is gas[i] - cost[i], the fuel you gain or lose.

How it works:

  • Sum every net into total. If the whole system has less gas than cost, no start works.
  • Keep a running tank from the current start. Add each net to it.
  • When tank drops below zero, the current start fails. Move start to the next station and reset tank to 0.
  • At the end, return start if total >= 0, else -1.

Why it is fast:

  • You walk the stations only once. So it is O(n).
  • You can skip every failed station in between. They had even less fuel for that same stretch, so none of them could survive it.
  • Greedy here means you jump the start forward past every station that just failed and trust it.

Here is a dry run on gas = [1, 2, 3, 4, 5], cost = [3, 4, 5, 1, 2]. Watch the tank reset and the start move to 3.

s0 net -2: tank=-2 < 0 -> start=1, tank=0

s1 net -2: tank=-2 < 0 -> start=2, tank=0

s2 net -2: tank=-2 < 0 -> start=3, tank=0

s3 net +3: tank=3

s4 net +3: tank=6

total = 0 >= 0 -> answer start = 3

Steps to Solve

  1. Keep a total of all nets and a running tank, both starting at 0. Set start = 0.
  2. Walk through the stations once. Compute each net as gas[i] - cost[i].
  3. Add the net to both total and tank.
  4. If tank drops below zero, set start to i + 1 and reset tank to 0.
  5. After the loop, if total is negative, return -1, because no start can finish.
  6. Otherwise return start.

This Python version keeps a total, a running tank, and a candidate start in plain variables.

gas_station.py
def can_complete_circuit(gas, cost):
total = 0 # net fuel across all stations
tank = 0 # running tank from the current start
start = 0 # candidate starting station
for i in range(len(gas)):
net = gas[i] - cost[i]
total += net
tank += net
if tank < 0: # current start failed
start = i + 1 # try the next station
tank = 0 # empty tank again
return start if total >= 0 else -1
gas = [1, 2, 3, 4, 5]
cost = [3, 4, 5, 1, 2]
print(can_complete_circuit(gas, cost))

The output of the above code will be:

3

Let us walk through the Python version line by line, because two ideas are packed into one short loop.

total = 0, tank = 0, start = 0 set up the three numbers. total sums every net to decide if the trip is even possible. tank is the fuel since the current start. start is the station we currently believe is the answer.

for i in range(len(gas)): walks every station once. There is no inner loop, which is exactly why this is fast.

net = gas[i] - cost[i] is the fuel you gain or lose at this station. Positive means you collect more than you spend.

total += net and tank += net add the net to both running sums. total never resets. tank does.

if tank < 0: is the failure check. If the tank goes negative, you cannot reach this station from the current start. So that start, and every station before this one in the stretch, is ruled out.

start = i + 1 jumps the start to the next station. tank = 0 empties the tank for the fresh start.

return start if total >= 0 else -1 gives the final answer. If the whole system had enough fuel, start is correct. If not, no start works, so return -1.

⏱️ Time and Space Complexity

The brute force tries every station as a start and may drive the full loop each time, so it is O(nΒ²). The greedy way keeps three numbers and one loop. So it trades nothing and still wins. That takes the time all the way down to O(n) with O(1) extra space.

Approach Time Complexity Space Complexity
Brute force (try every start) O(nΒ²) O(1)
Greedy total and tank O(n) O(1)

Tip

The two facts work together. The total tells you whether any answer exists. The running tank tells you where it starts. Explain both out loud, and the interviewer sees you understand why one pass is enough.

🧩 Key Takeaways

  • βœ… The net at each station is gas[i] - cost[i], the fuel you gain or lose there.
  • βœ… If the total of all nets is negative, no start can finish, so return -1.
  • βœ… When the running tank goes below zero, move the start to the next station and reset the tank.
  • βœ… You can skip all the failed stations in between, because they had even less fuel for that stretch.
  • βœ… This runs in O(n) time with O(1) extra space, beating the O(nΒ²) brute force.

Check Your Knowledge

4 questions Show quiz Hide quiz

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What does the Gas Station problem ask you to return?

    Why: You return the index of a valid starting station, or -1 if no start can complete the circuit.

  2. 2

    What is the net fuel at station i?

    Why: Net fuel is gas[i] - cost[i], how much you gain or lose at that station.

  3. 3

    When the running tank drops below zero, what does the greedy solution do?

    Why: A negative tank rules out the current start and every station in the stretch, so start jumps to i + 1.

  4. 4

    What is the time and space complexity of the greedy approach?

    Why: One pass over the stations is O(n), and three counters use O(1) extra space.

πŸš€ What’s Next?