Simple O(n), O(1) space solution, JS


  • 4
    R
    var canCompleteCircuit = function(gas, cost) {
        carFuel = 0;
        streak = 0;
        for(i = 0; i <= gas.length*2; i++) {
            carFuel += gas[i%gas.length];
            carFuel -= cost[i%cost.length];
            if(carFuel < 0) {
                carFuel = 0;
                streak = -1;
            }
            if(streak === gas.length)
                return i-streak;
            
            streak++;
        }
        return -1;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.