Gas Station LeetCode solution in JavaScript

1
var canCompleteCircuit = function (gas, cost) {
2
const len = gas.length;
3
// scan forward from the current index
4
const scan = (i) => {
5
let numTries = 0;
6
let tank = 0;
7
let c = 0;
8
while (numTries <= len) {
9
tank -= c;
10
if (tank < 0) return -1;
11
// if we made it back around, and we have gas, return the index, we made it!
12
if (numTries === len && tank >= 0) {
13
return i;
14
}
15
tank += gas[i];
16
c = cost[i];
17
i++;
18
if (i === len) i = 0; // if we hit the end, bounce back to zero
19
numTries++;
20
}
21
return -1;
22
};
23

24
for (let i = 0; i < len; i++) {
25
if (!gas[i]) continue; // no gas / zero gas so let's just move on
26
let index = scan(i);
27
if (~index) return index; // if it's not -1, return it
28
}
29

30
return -1;
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0