find the kth least frequent element in an array in php

One way to solve this problem is to use counting sort to count the frequency of each element in the array and then sort the counts to find the kth least frequent element.

Here's the code to find the kth least frequent element in an array in PHP:

main.php
function kthLeastFrequent($arr, $k) {
  // count frequency of each element in the array
  $count = array();
  foreach ($arr as $elem) {
    if (array_key_exists($elem, $count)) {
      $count[$elem]++;
    } else {
      $count[$elem] = 1;
    }
  }
  
  // sort the counts in ascending order
  asort($count);
  
  // get the kth least frequent element
  $kth = null;
  $i = 0;
  foreach ($count as $elem => $freq) {
    $i++;
    if ($i == $k) {
      $kth = $elem;
      break;
    }
  }
  
  return $kth;
}

// example usage
$arr = array(1, 2, 3, 2, 2, 3, 4, 4, 5);
$k = 3;
$kthLeastFrequentElem = kthLeastFrequent($arr, $k);
echo "The ".$k."th least frequent element in the array is ".$kthLeastFrequentElem; // output: The 3th least frequent element in the array is 5
772 chars
34 lines

In the code above, we first count the frequency of each element in the array using a foreach loop and an associative array called $count. Then we use the built-in asort function to sort this array in ascending order of counts. Finally, we loop through the sorted array and return the kth least frequent element.

gistlibby LogSnag