find the kth least common element in an array in javascript

To find the kth least common element in an array, we need to first sort the array and then iterate through it, counting the frequency of each element. Once we know the frequency of each element, we can sort by frequency and return the kth least frequent element.

Here is the code:

index.tsx
function kthLeastCommonElement(arr, k) {
  const frequency = {};
  for(let i = 0; i < arr.length; i++) {
    frequency[arr[i]] = frequency[arr[i]] + 1 || 1;
  }
  
  const sortedByFrequency = Object.keys(frequency).sort((a, b) => frequency[a] - frequency[b]);
  
  return sortedByFrequency[k - 1];
}

const arr = [1, 2, 2, 3, 4, 4, 4, 5, 5];
const k = 3;

const kthLeastCommon = kthLeastCommonElement(arr, k);
console.log(kthLeastCommon); // 3
444 chars
17 lines

In this code, we first iterate through the array and count the frequency of each element using an object as a hash map. Then, we sort the keys of this object by their frequency. Finally, we return the kth element of this sorted array (noting that arrays are zero-indexed, so we subtract 1 from k).

gistlibby LogSnag