Greedy Algorithms · Circular route · One pass

Gas Station Visualizer

What is Gas Station

There are n gas stations on a circle. gas[i] is the fuel you collect at station i. cost[i] is the fuel required to drive from station i to station i + 1. You start with an empty tank and may begin at one station. Return the starting index that completes one full circuit, or -1 when no station works. If a start exists, it is unique.

Example 1. Start at station 3. The tank stays non-negative all the way around: 3 to 4 to 0 to 1 to 2 and back to 3.

gas  = 1 2 3 4 5
cost = 3 4 5 1 2
Output: 3

Example 2. Total gas is 9 and total cost is 10, so the circuit is impossible.

gas  = 2 3 4
cost = 3 4 3
Output: -1

Approach

Try every startSimulate the circle from each station. That is correct and costs O(n2) because each start may drive through every station.
One forward passIf total gas is below total cost, answer -1. Otherwise walk once. Whenever the tank goes negative, every station in that failed stretch is impossible as a start, because each of them would have arrived at the failure with even less fuel. The next station becomes the candidate and the tank resets to 0.

Interactive visualization

Step through the greedy choice

The walk starts on the first pseudocode line. Next and Play move one step at a time, and the highlighted line is the line that just ran.

total = 0, tank = 0, start = 0
for i = 0 to n - 1:
tank += gas[i] - cost[i]; total += the same
if tank < 0: start = i + 1; tank = 0
if total < 0: return -1 else return start
Step 0 Answer —

Complexity

PieceCostWhy
TimeO(n)Each station is visited once.
SpaceO(1)Tank, total surplus, and the candidate start.
Greedy choiceRestart after a dipA station inside a failed stretch cannot be the unique start.

Implementation

def can_complete_circuit(gas, cost): total = tank = start = 0 for i in range(len(gas)): diff = gas[i] - cost[i] total += diff tank += diff if tank < 0: start = i + 1 tank = 0 return -1 if total < 0 else start