In this Leetcode Gas Station problem solution, There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.

Given two integer arrays of 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.

Leetcode Gas Station problem solution


Problem solution in Python.

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        start=0
        gr=0
        shortage=0
        tank=0
        for i in range(len(gas)):
            gr=gas[i]-cost[i]
            tank+=gr
            if tank<0:
                start=i+1
                tank=0
            shortage+=gr
        if(shortage>=0):
            return start
        return -1



Problem solution in Java.

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int startPointIdx = 0;
        int additionalGasNeeded = 0;
        int totalGasInTask = 0;
        for (int i = 0; i < gas.length; i++) {
            totalGasInTask = totalGasInTask + gas[i] - cost[i];
            if (totalGasInTask < 0) {
                additionalGasNeeded = additionalGasNeeded + totalGasInTask;
                totalGasInTask = 0;
                startPointIdx = i + 1;
            }
        }
        if (totalGasInTask + additionalGasNeeded >= 0) {
            return startPointIdx;
        } else {
            return -1;            
        }
    }
}


Problem solution in C++.

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int sum1=accumulate(begin(gas),end(gas),0);
        int sum2=accumulate(begin(cost),end(cost),0);
        if(sum1<sum2)return -1;
        int maxin=0;
        int curr=0;
        int n=gas.size();
        for(int i=0;i<n;i++)
        {
            curr+=gas[i]-cost[i];
            if(curr<0)
            {
                maxin=i+1;
                curr=0;
            }
        }
        return maxin;
    }
};


Problem solution in C.

int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize) {
    int i=0,tail = -1,over = 0, sum = 0;
    while(1)
    {
        tail++;
        if(tail == gasSize)
            tail = 0;
        sum += (gas[tail]-cost[tail]);
        if(sum >= 0)
        {
            if(((i==0)&&(tail==gasSize-1))||((i!=0)&&(tail==i-1)))
            {
                over = 1;
                break;
            }
        }
        while(sum < 0)
        {
            sum -= (gas[i]-cost[i]);
            i++;
            if(i == gasSize)
            break;
        }
        if(i == gasSize)
            break;
    }
    return over==0?-1:i;
}