AlgoTales · Roadmap

Gas station

Advanced · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The gas station puzzle asks where to begin on a circular route so you never run out of fuel, when each stop gives some fuel and each leg costs some. A single pass, restarting whenever your balance goes negative, finds the answer.

Practical use cases

  • Web app: EV charging loop planner. A fleet app has a ring route with charging stops giving some kilometres of range and legs using some. It picks the starting stop from which a vehicle can complete the full loop without getting stranded, in one pass over the stops.
  • Web app: Running balance in a passbook. A banking or wallet app checks a repeating cycle of credits and debits, such as salary then rent then bills. Finding the starting point in the cycle where the balance never dips below zero is the same pattern.
  • Web app: Circular delivery route. A courier picks up and drops off parcels around a ring road, with the van's load changing at each stop. The app finds the stop to start from so capacity or fuel is never negative. Without it the app would try each starting stop in turn, which becomes slow when the ring has hundreds of stops.
  • System: Circular train lines. Loop lines and ring roads in transport planning use the same running-balance logic to check a service can be sustained all the way round. The key insight is that if the balance goes negative at some stop, none of the earlier stops in that stretch could have been a good start either.

The story: The Auto-Rickshaw Ring Road

Mira's uncle drove an auto-rickshaw. One Diwali morning he wanted to go all the way around the ring road, which has five petrol pumps. Each pump gave him some litres, and each stretch of road to the next pump burned some litres. His tank was empty to start, so he had to pick the right pump to begin from.

Uncle tried pump 0 first. He got 1 litre but needed 3 to reach the next pump. Stuck! Then pump 1: 2 litres, but needed 4. Stuck again. He kept going home and trying again, and each attempt wasted half the morning.

Mira spotted a pattern: "If you start at pump 0 and get stuck at pump 2, then starting at pump 1 will get stuck even earlier, because you would have arrived at pump 1 with even less petrol than if you had started at pump 0!" So when the tank goes negative at pump i, skip all of those starts and try pump i+1.

One more check: add up all the petrol and all the road needs. If petrol is less than the need in total, no pump will work. Otherwise, the last candidate left standing is the answer. That is the gas station problem: a greedy walk that needs just one trip around the ring.

How to spot this problem, and where you need it

You travel around a loop gaining something at each stop and spending something between stops, and need to find the start point where you never go below zero, or learn that none exists.

Signs you need it

  • The route or process is circular, and each step adds to a balance and then subtracts from it.
  • The question says "find the starting point" and "never run out", with the answer being an index or none.
  • You are trying each possible start and simulating the whole loop, which takes too long on many stops.

Where to use it in a project

  • Fleet, EV and delivery loop planning where fuel, charge or capacity changes at each stop.
  • Cyclic payment or budget schedules where the balance must never go negative.

The solution

First check the total: if all the gains are less than all the costs, no start works. Otherwise walk around once keeping a running balance. Whenever the balance falls below zero, reset it to zero and say the next stop is the new candidate start, because no stop in between could have worked either. After one pass, the candidate is the answer.

Payoff: Before: simulating the loop from each of 1,000 stops, a million steps. After: one pass of 1,000 steps names the start.

Explain it like I am 8

You walk around a circle of sweet shops. Each shop hands you some sweets, but the walk to the next costs you some sweets. If your bag ever hits "less than zero", forget that start and begin fresh at the next shop. If the sweets overall are enough, your last fresh start is the winner.

How it works, step by step

  1. Compute the net gain at each pump: gas[i] - cost[i].
  2. If the total net gain is negative, answer -1: no start can work.
  3. Walk around once, keeping a running tank and a candidate start (initially 0).
  4. If the tank goes below zero at pump i, set start = i + 1 and reset the tank to 0.
  5. After the walk, start is the answer (it is unique when the total is non-negative).

The code in four languages

PHP

<?php
// Returns the starting pump index that completes the circle, or -1.
function canCompleteCircuit(array $gas, array $cost): int {
    $total = 0;     // overall petrol minus overall need
    $tank = 0;      // petrol in the tank since our candidate start
    $start = 0;
    for ($i = 0; $i < count($gas); $i++) {
        $gain = $gas[$i] - $cost[$i];
        $total += $gain;
        $tank += $gain;
        if ($tank < 0) {          // stuck: no start from $start..$i can work
            $start = $i + 1;
            $tank = 0;
        }
    }
    return $total >= 0 ? $start : -1;
}

echo canCompleteCircuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]) . PHP_EOL;   // 3
echo canCompleteCircuit([2, 3, 4], [3, 4, 3]);                          // -1

JavaScript

// Returns the starting pump index that completes the circle, or -1.
function canCompleteCircuit(gas, cost) {
  let total = 0;     // overall petrol minus overall need
  let tank = 0;      // petrol in the tank since our candidate start
  let start = 0;
  for (let i = 0; i < gas.length; i++) {
    const gain = gas[i] - cost[i];
    total += gain;
    tank += gain;
    if (tank < 0) {            // stuck: no start from start..i can work
      start = i + 1;
      tank = 0;
    }
  }
  return total >= 0 ? start : -1;
}

console.log(canCompleteCircuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]));   // 3
console.log(canCompleteCircuit([2, 3, 4], [3, 4, 3]));               // -1

Java

public class Main {
    // Returns the starting pump index that completes the circle, or -1.
    static int canCompleteCircuit(int[] gas, int[] cost) {
        int total = 0;     // overall petrol minus overall need
        int tank = 0;      // petrol in the tank since our candidate start
        int start = 0;
        for (int i = 0; i < gas.length; i++) {
            int gain = gas[i] - cost[i];
            total += gain;
            tank += gain;
            if (tank < 0) {           // stuck: no start from start..i can work
                start = i + 1;
                tank = 0;
            }
        }
        return total >= 0 ? start : -1;
    }

    public static void main(String[] args) {
        System.out.println(canCompleteCircuit(new int[]{1, 2, 3, 4, 5}, new int[]{3, 4, 5, 1, 2}));   // 3
        System.out.println(canCompleteCircuit(new int[]{2, 3, 4}, new int[]{3, 4, 3}));               // -1
    }
}

Go

package main

import "fmt"

// canCompleteCircuit returns the starting pump index that completes the circle, or -1.
func canCompleteCircuit(gas, cost []int) int {
	total := 0 // overall petrol minus overall need
	tank := 0  // petrol in the tank since our candidate start
	start := 0
	for i := range gas {
		gain := gas[i] - cost[i]
		total += gain
		tank += gain
		if tank < 0 { // stuck: no start from start..i can work
			start = i + 1
			tank = 0
		}
	}
	if total >= 0 {
		return start
	}
	return -1
}

func main() {
	fmt.Println(canCompleteCircuit([]int{1, 2, 3, 4, 5}, []int{3, 4, 5, 1, 2})) // 3
	fmt.Println(canCompleteCircuit([]int{2, 3, 4}, []int{3, 4, 3}))             // -1
}

Time: O(n) · Extra space: O(1). One lap around the circle and just three running numbers. Trying every start would cost O(n²).

Watch out for

  • Trying every starting pump separately, which is slow, instead of skipping bad stretches at once.
  • Forgetting the total check. Without it, you might return a start even when petrol is short overall.
  • Not resetting the tank to zero after moving the start.

Quick check

  1. The tank goes negative at pump 4 while starting from pump 2. Which starts can we rule out?
    • Only pump 2
    • None
    • Pumps 2, 3 and 4
  2. What does it mean if total petrol is less than total need?
    • No start works: return -1
    • Start at 0
    • Try twice around
  3. How many times do we go around the circle?
    • n times
    • Once
    • log n times