Algorithms · Visualized
Gas Station
Greedy
Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.
Given gas available and cost to travel between stations arranged in a circle, find the starting station from which you can complete a full circuit without running out of gas. Time: O(n) average, O(n) worst; space: O(1).
Big-O: Works when the problem has optimal substructure + greedy-choice property — e.g. intervals, Huffman, fractional knapsack.
Gas Station
GreedyGiven gas available and cost to travel between stations arranged in a circle, find the starting station from which you can complete a full circuit without running out of gas. The greedy insight: if the total gas is at least the total cost, a solution exists, and it starts right after the point where your running fuel tank total hits its lowest point.
How Gas Station Works
- Check if the total gas across all stations is at least the total cost — if not, no solution exists, return -1.
- Track a running 'tank' total (gas[i] - cost[i] summed so far) and a candidate 'start' index, both beginning at 0.
- Loop through each station, adding (gas[i] - cost[i]) to the running tank total.
- If the running tank total ever drops below 0, you can't have started at or before this station — reset the candidate start to the next station, and reset the running tank total to 0.
- After the loop, the recorded candidate 'start' is the answer (guaranteed valid since total gas ≥ total cost).
Gas Station Worked Example
Input: {gas: [1, 2, 3, 4, 5], cost: [3, 4, 5, 1, 2]}
Total gas=15, total cost=15, equal → a solution exists. Running total: i0: 1-3=-2 (below 0) → reset start=1, total=0. i1: 2-4=-2 (below0) → reset start=2, total=0. i2: 3-5=-2 (below0) → reset start=3, total=0. i3: 4-1=3, total=3. i4: 5-2=3, total=6. Loop ends with start=3 still valid. Answer: starting station index 3.
def gas_station(gas, cost):
if sum(gas) < sum(cost):
return -1
start = tank = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start = i + 1
tank = 0
return startBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Gas Station Time & Space Complexity
When to Use Gas Station
- Route planning and logistics: finding a feasible starting depot given fuel/resource constraints along a circular route.
- A neat example of how a local greedy reset rule solves a seemingly global search problem in one pass.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.