How to find the element with minimum occurrences in an array with JavaScript

1 Answer

0 votes
/**
 * Finds the element with the minimum occurrences in an array.
 * 
 * @template T
 * @param {T[]} array - The input array to process.
 * @returns {T | null} The element with the lowest frequency, or null if empty.
 */
function findMinOccurrence(array) {
    if (!Array.isArray(array) || array.length === 0) {
        return null;
    }

    // 1. Tally element frequencies using a Map (handles any type, including primitives and objects)
    const counts = array.reduce((acc, item) => {
        acc.set(item, (acc.get(item) || 0) + 1);
        return acc;
    }, new Map());

    // 2. Find the entry with the minimum count in O(K) time
    let minElement = null;
    let minCount = Infinity;

    for (const [item, count] of counts.entries()) {
        if (count < minCount) {
            minCount = count;
            minElement = item;
        }
    }

    return minElement;
}

// Example usage:
const arr = [1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3];

const result = findMinOccurrence(arr);

if (result !== null) {
    console.log(result); // Output: 5
} else {
    console.log("The array was empty or invalid.");
}


/*
run:

5

*/

 



answered Sep 25 by avibootz
...