1
var getCollisionTimes = function (cars) {2
// create a stack to hold all the indicies of the cars that can be hit3
const possibleCarsToHit = [];4
const result = new Array(cars.length).fill(-1);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 hitting8
// the car in front of them9
// you can also think of this as if the current car will hit the car before or after being absorbed by10
// the slower car in front.12
possibleCarsToHit.length &&13
result[possibleCarsToHit[possibleCarsToHit.length - 1]] >= 015
const nextCarIndex = possibleCarsToHit[possibleCarsToHit.length - 1];16
const timeToCatchNextCar = getTimeToCatchNextCar(20
const timeToCatchNextNextCar = result[nextCarIndex];22
timeToCatchNextCar > 0 &&23
timeToCatchNextCar <= timeToCatchNextNextCar28
// pop off the stack because the car was absorbed by the next car29
// before getting hit by the current car30
possibleCarsToHit.pop();32
if (possibleCarsToHit.length) {33
const nextCarIndex = possibleCarsToHit[possibleCarsToHit.length - 1];34
result[i] = getTimeToCatchNextCar(cars[i], cars[nextCarIndex]);36
possibleCarsToHit.push(i);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;