GreedyAnimated
Gas Station Problem
If the tank goes negative, restart after that station.
Time
O(n)
Extra space
O(1)
Use it for
Finding a start for a circular route.
How it works
- Stations sit on a circle. You gain gas[i] at station i and spend cost[i] to reach the next one.
- Drive from a candidate start, adding gas[i] − cost[i] to the tank.
- If the tank goes negative, no station between the start and here can be the start either, so the next station becomes the new candidate and the tank resets.
- If the total gas is at least the total cost, the last candidate works. One pass, O(n).
Watch it run
Loading animation…