There are n gas stations along a circular route, where the amount of gas at the i-th station is gas[i]. It costs cost[i] of gas to travel from station i to i + 1. You begin the journey with an empty tank at one of the gas stations.
The standard greedy algorithm claims that if the total gas is at least the total cost, a solution is guaranteed to exist, and whenever your running tank drops below 0 at station i, you can safely restart your search from station i + 1. Why are we allowed to skip all intermediate stations between start and i?
The Gas Station problem is one of the most elegant examples of the Greedy Elimination Proof. Let’s break down the mathematical invariant that allows you to skip stations with 100% confidence.
1. The Two Fundamental Theorems
Theorem 1: Total Balance Invariant
If $sum gas[i] ge sum cost[i]$, there is guaranteed to be at least one valid starting station that completes the entire circuit.
Why? Because the total net balance $sum (gas[i] – cost[i]) ge 0$. If you graph the cumulative fuel sum along the circle, the lowest dip (the absolute minimum point on the graph) is the optimal starting point! Starting right after that lowest dip means your tank will never dip below zero!
Theorem 2: The Greedy Skip Invariant
Suppose you start at station
Aand successfully reach stationB, but you fail to travel fromBtoB + 1(your tank drops below 0).Claim: No station
CbetweenAandB(i.e. $A le C le B$) can be the starting station!Proof:
Aand reachedC, the gas you had in your tank upon arriving atCwas $ge 0$.C, you still starved and died atB!Cfrom scratch (with an empty tank, zero bonus gas), you would run out of fuel at or before stationB!Therefore, every single station from
AtoBis mathematically disqualified in one fell swoop! The next possible candidate can only beB + 1.Clean Python 3.12 Implementation
Complexity Breakdown
O(N). Exactly one single pass through the array. Zero nested loops.O(1). Exactly 3 scalar integers tracking running totals.Here is the clean C++20 Single-Pass Greedy solution for the Gas Station problem.
Complexity: Strictly
O(N)time andO(1)auxiliary space.