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

1 Answer

0 votes
/**
 * Finds the element with the minimum number of occurrences in an array.
 * 
 * @template T - The type of elements in the array.
 * @param array - The input array to evaluate.
 * @returns The least frequent element, or `undefined` if the array is empty or invalid.
 */
export function findMinOccurrence<T>(array: readonly T[]): T | undefined {
    if (!array || array.length === 0) {
        return undefined;
    }

    // 1. Tally element frequencies O(N)
    const counts: Map<T, number> = new Map<T, number>();
    for (const item of array) {
        const currentCount: number = counts.get(item) ?? 0;
        counts.set(item, currentCount + 1);
    }

    // 2. Find the entry with the minimum count O(K)
    let minElement: T | undefined = undefined;
    let minCount: number = Infinity;

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

    return minElement;
}

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

const result: number | undefined = findMinOccurrence<number>(arr);

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


/*
run:

5

*/

 



answered Sep 25 by avibootz
edited Sep 25 by avibootz
...