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

Greedy

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

  1. Check if the total gas across all stations is at least the total cost — if not, no solution exists, return -1.
  2. Track a running 'tank' total (gas[i] - cost[i] summed so far) and a candidate 'start' index, both beginning at 0.
  3. Loop through each station, adding (gas[i] - cost[i]) to the running tank total.
  4. 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.
  5. 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.

Gas StationO(n)
Find a starting station that completes the circuit using net gains.
-2
0
-2
1
-2
2
3
3
3
4
Step 1 / 10
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Gas Station: net[i] = gas[i] − cost[i]. Greedy — restart when the tank goes negative.
Python · Greedy Algorithms in Code
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 start

Behind 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

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.