find the kth least common element in an array in php

To find the kth least common element in an array, we can use the following algorithm:

  1. Create an associative array to store the count of each element in the given array.
  2. Sort the count array in ascending order.
  3. Traverse the sorted count array and check if the kth least common element is found.
  4. If found, return the corresponding element from the associative array.
  5. If not found, return null or any other suitable value to indicate that the kth least common element is not present in the array.

Here's the PHP code that implements the above algorithm:

main.php
function find_kth_least_common_element(array $arr, int $k) {
    $count_arr = array_count_values($arr);
    asort($count_arr); // sort by count in ascending order
    $i = 1;
    foreach ($count_arr as $key => $count) {
        if ($i == $k) {
            return $key;
        }
        $i++;
    }
    return null; // kth least common element not found
}
356 chars
13 lines

Example usage:

main.php
$arr = [1, 2, 3, 2, 1, 4, 4, 5];
$k = 3; // find 3rd least common element
$result = find_kth_least_common_element($arr, $k);
if ($result !== null) {
    echo "The $k-th least common element is $result";
} else {
    echo "No such element found";
}
// Output: The 3-rd least common element is 3
294 chars
10 lines

Note: This solution has a time complexity of O(n log n) due to sorting. We can optimize it to O(n) by using a modified counting sort algorithm, but it requires additional memory.

gistlibby LogSnag