find the kth least frequent element in an array in javascript

To find the kth least frequent element in an array, we can use counting sort to create a frequency count of each element in the array, and then sort the frequency array in ascending order to find the kth least frequent element.

Here's the code:

index.tsx
function kthLeastFrequent(arr, k) {
  // Create frequency count of each element in array
  const freq = {};
  for (const num of arr) {
    freq[num] = (freq[num] || 0) + 1;
  }

  // Sort frequency array in ascending order
  const sortedFreq = Object.entries(freq).sort((a, b) => a[1] - b[1]);

  // Return kth least frequent element
  return sortedFreq[k-1][0];
}
365 chars
14 lines

Here's how to use the function:

index.tsx
const arr = [1, 2, 3, 3, 4, 4, 4, 5];
console.log(kthLeastFrequent(arr, 2)); // Output: 2 (2 is the 2nd least frequent element in the array)
141 chars
3 lines

gistlibby LogSnag