There are n
gas stations along a circular route, where the amount of gas at the i-th
station is represented by gas[i]
, and the cost to travel from the i-th
station to the (i+1)-th
station is represented by cost[i]
.
You have a car with an unlimited gas tank, and it costs cost[i]
of gas to travel from the i-th
gas station to the (i+1)-th
station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas
and cost
, return the starting gas station’s index if you can travel around the circuit once in the clockwise direction, otherwise return -1
. If there exists a solution, it is guaranteed to be unique.
gas
and cost
will have the same non-negative length n
, where 1 <= n <= 10^4
.gas[i]
and cost[i]
can be zero.-1
.i
to i+1
, none of the stations before i
can be the starting point.def canCompleteCircuit(gas, cost):
total_gas, total_cost = 0, 0
tank, start_index = 0, 0
for i in range(len(gas)):
total_gas += gas[i]
total_cost += cost[i]
tank += gas[i] - cost[i]
# If tank is negative, reset the start position
if tank < 0:
start_index = i + 1
tank = 0
# If total gas is less than total cost, it's impossible
return start_index if total_gas >= total_cost else -1
The solution works in a single pass through the list, so the time complexity is (O(n)), where (n) is the number of gas stations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?