JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

JavaScript

function gcd(a, b) {
    return b === 0 ? a : gcd(b, a % b);
}

function lcm(a, b) {
    return (a * b) / gcd(a, b);
}

function findEarliestCommonTime(truckTimes) {
    let commonTime = truckTimes[0];

    for (let i = 1; i < truckTimes.length; i++) {
        commonTime = lcm(commonTime, truckTimes[i]);
    }

    // Check if the trucks are never again at the headquarters at the same time
    for (const time of truckTimes) {
        if (commonTime % time !== 0) {
            return 1;
        }
    }

    return commonTime;
}

// Example usage
const truckTimes = [1, 3, 2];
console.log(findEarliestCommonTime(truckTimes)); // Output: 4