find the kth least frequent element in an array in typescript

To find the kth least frequent element in an array in TypeScript, we can use an object to keep track of the frequency of each element in the array. We can then sort the array based on the frequency of each element, and return the kth element.

index.ts
function kthLeastFrequentElement(arr: any[], k: number): any {
  const freqMap: { [key: string]: number } = {};
  arr.forEach(elem => {
    freqMap[elem] = (freqMap[elem] || 0) + 1;
  });

  const sortedArr = Object.entries(freqMap).sort((a, b) => a[1] - b[1]);

  return sortedArr[k - 1][0];
}
295 chars
11 lines

We first create an empty freqMap object to keep track of the frequency of each element in the array. We loop through each element in the array using forEach, and for each element, we check if it exists as a key in freqMap. If it does, we increment the corresponding value by 1. If it does not, we create a new key with a value of 1.

Next, we use Object.entries to convert the object into an array of key-value pairs. We then sort the resulting array based on the frequency of each element, with the least frequent elements appearing first.

Finally, we return the kth least frequent element by accessing the k-1th element in the sorted array, and returning its key (which represents the element in the array).

gistlibby LogSnag