Car Fleet II LeetCode solution in JavaScript

1
var getCollisionTimes = function (cars) {
2
// create a stack to hold all the indicies of the cars that can be hit
3
const possibleCarsToHit = [];
4
const result = new Array(cars.length).fill(-1);
5

6
for (let i = cars.length - 1; i >= 0; i--) {
7
// if there are cars to hit, check if the current car will hit the car before or after hitting
8
// the car in front of them
9
// you can also think of this as if the current car will hit the car before or after being absorbed by
10
// the slower car in front.
11
while (
12
possibleCarsToHit.length &&
13
result[possibleCarsToHit[possibleCarsToHit.length - 1]] >= 0
14
) {
15
const nextCarIndex = possibleCarsToHit[possibleCarsToHit.length - 1];
16
const timeToCatchNextCar = getTimeToCatchNextCar(
17
cars[i],
18
cars[nextCarIndex]
19
);
20
const timeToCatchNextNextCar = result[nextCarIndex];
21
if (
22
timeToCatchNextCar > 0 &&
23
timeToCatchNextCar <= timeToCatchNextNextCar
24
) {
25
break;
26
}
27

28
// pop off the stack because the car was absorbed by the next car
29
// before getting hit by the current car
30
possibleCarsToHit.pop();
31
}
32
if (possibleCarsToHit.length) {
33
const nextCarIndex = possibleCarsToHit[possibleCarsToHit.length - 1];
34
result[i] = getTimeToCatchNextCar(cars[i], cars[nextCarIndex]);
35
}
36
possibleCarsToHit.push(i);
37
}
38
return result;
39
};
40

41
function getTimeToCatchNextCar(leftCar, rightCar) {
42
const [leftCarPosition, leftCarSpeed] = leftCar;
43
const [rightCarPosition, rightCarSpeed] = rightCar;
44
const distanceToCatchCar = rightCarPosition - leftCarPosition;
45
const differenceInSpeed = leftCarSpeed - rightCarSpeed;
46
return differenceInSpeed > 0 ? distanceToCatchCar / differenceInSpeed : -1;
47
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0