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
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.
1FUNCTION canCompleteCircuit(gas, cost):2 set tank = 0 and start = 03 FOR i from 0 to length of gas - 1:4 add gas[i] - cost[i] to tank5 IF tank < 0:6 set start = i + 17 reset tank = 08 END IF9 END FOR10 RETURN start if total gas >= total cost, otherwise -111END FUNCTION
← / → step · space play · Home restart