JavaScript Challenge - Calculate the Mean and Mode, Calculate the Mean and Mode

Sorry, I wrongly “reply”. I just want to send my answer :smile:

The optimal solution should be O(n), cuz you iterate the array twice, first you calculate the occurances, second you try to retrive the largest occurance number. No recalculation.

function statsFinder(numbers) {
// Calculate mean
// Time complexity: O(n), where n is the number of elements in the array
const mean = numbers.reduce((sum, num) => sum + num, 0) / numbers.length;

// Calculate mode
// Time complexity: O(n), where n is the number of elements in the array
const count = {};
let maxCount = 0;
let mode = null;

for (const num of numbers) {
    count[num] = (count[num] || 0) + 1;

    if (count[num] > maxCount) {
        maxCount = count[num];
        mode = num;
    }
}

return [mean, mode];

}

console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300]))

// Leave this so we can test your code:
module.exports = statsFinder;

function statsFinder(numbers) {
// Calcular la media
const mean = numbers.reduce((acc, curr) => acc + curr, 0) / numbers.length;

// Calcular la moda
const occurrences = {};
let maxCount = 0;
let mode = null;
numbers.forEach(number => {
occurrences[number] = (occurrences[number] || 0) + 1;
if (occurrences[number] > maxCount) {
maxCount = occurrences[number];
mode = number;
}
});

// Crear una lista con la media y la moda
const result = [mean, mode];
return result;
}

console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300]))

// Leave this so we can test your code:
module.exports = statsFinder;