Visualize

Pattern visualizer

Gas Station

The insight: if the running tank total from some candidate start turns negative by the time you reach station i, every station between that start and i is also a dead end — starting from any of them just means giving up part of the surplus that got you that far, so they'd run out even sooner. That's why the moment tank dips negative, it's safe to jump the candidate start all the way to i+1 and reset to zero, instead of retrying every in-between station one by one. One linear pass — tank += gas[i]-cost[i], reset on negative — is enough because, as long as total gas >= total cost, exactly one starting point survives every reset and completes the circuit. Animated on: Given gas and cost arrays for n gas stations arranged in a circle, find the starting station index that allows traveling around the circuit once. Return -1 if impossible..

Greedy

time O(n)space O(1)step 1 / 8
1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
line 1

Initialize tank=0, start=0, i=0. Total gas = 1+2+3+4+5 = 15, total cost = 3+4+5+1+2 = 15. Tank will track net gain across the circuit.

Pseudocode
1FUNCTION canCompleteCircuit(gas, cost):
2 set tank = 0 and start = 0
3 FOR i from 0 to length of gas - 1:
4 add gas[i] - cost[i] to tank
5 IF tank < 0:
6 set start = i + 1
7 reset tank = 0
8 END IF
9 END FOR
10 RETURN start if total gas >= total cost, otherwise -1
11END FUNCTION

← / → step · space play · Home restart

Where to practice Greedy