Skip to content
BASA DSA

Gas Station

MediumGreedy

Stations form a circle. Starting with an empty tank at i, collect gas[i] then spend cost[i] to reach the next station. Return the index from which one complete lap is possible, or -1.

Example 1

Input
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
Output
3

Explanation

Starting at 3 accumulates enough surplus at 3 and 4 to cover deficits at 0,1,2.

Example 2

Input
gas = [2,2]
cost = [3,3]
Output
-1

Explanation

Total gas 4 is below total cost 6, so no start works.

Example 3

Input
gas = [5]
cost = [4]
Output
0

Explanation

Station 0 supplies 5 and costs 4, permitting the one-station lap.

Constraints

  • 1 <= number of stations <= 100000
  • gas and cost have equal lengths
  • Values are nonnegative <= 10000
  • If a solution exists its index is unique

Function contractcanCompleteCircuitArguments: json, json
Loading draft…
SolutionRuns on your device
Loading draft…