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

1 Answer

0 votes
declare(strict_types=1);

/**
 * Finds the element with the minimum occurrences in an array.
 *
 * @param array<int|string> $array Input array containing int or string scalar values.
 * @return int|string|null The least frequent element, or null if the array is empty.
 */
function findMinOccurrence(array $array): int|string|null
{
    if (empty($array)) {
        return null;
    }

    // 1. Tally element frequencies (O(N) time complexity)
    $counts = array_count_values($array);

    // 2. Sort associative array by value ascending while maintaining key associations
    asort($counts);

    // 3. Extract the key of the first element (the one with the lowest count)
    return array_key_first($counts);
}

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

$result = findMinOccurrence($arr);

if ($result !== null) {
    echo $result . PHP_EOL; // Output: 5
} else {
    echo "The array was empty." . PHP_EOL;
}



/*
run:

5

*/

 



answered Sep 25 by avibootz
...