Skip to content
StackDecode
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

  1. Stations sit on a circle. You gain gas[i] at station i and spend cost[i] to reach the next one.
  2. Drive from a candidate start, adding gas[i] − cost[i] to the tank.
  3. 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.
  4. If the total gas is at least the total cost, the last candidate works. One pass, O(n).

Watch it run

Loading animation…