find the kth most frequent element in an array in typescript

To find the kth most frequent element in an array in TypeScript, we can make use of hash tables and sorting.

We can first create a hash table to store the frequency of each element in the array. We can then sort these frequencies in descending order so that the most frequent elements appear first. Finally, we can return the kth element from the sorted frequency array.

Here's the TypeScript code:

index.ts
function kthMostFrequentElement(arr: number[], k: number): number {
  const frequency: Map<number, number> = new Map();
  
  // Count the frequency of each element in the array
  for (let i = 0; i < arr.length; i++) {
    const num = arr[i];
    frequency.set(num, (frequency.get(num) || 0) + 1);
  }

  // Sort the frequency map in descending order
  const sortedFrequency = [...frequency.entries()].sort((a, b) => b[1] - a[1]);

  // Return the kth most frequent element
  return sortedFrequency[k - 1][0];
}
511 chars
16 lines

Here, we create a Map called frequency to store the frequency of each element in the array. We use a for loop to iterate through the array, incrementing the count for each element in the Map.

We then use the entries method to get an array of all the entries in frequency, which we then sort in descending order of the frequency count using the sort method.

Finally, we return the kth most frequent element by getting the k-1th element of the sorted frequency array, which is an array of [value, frequency] tuples, and returning the value element.

gistlibby LogSnag