find the kth least common element in an array in typescript

To find the kth least common element in an array, we need to first sort the array and then count the frequency of each element. Finally, we can return the kth least common element.

Here is the TypeScript code to find kth least common element in an array:

index.ts
function kthLeastCommonElement(arr: number[], k: number): number {
  arr.sort((a: number, b: number) => a - b ); // Sorting array in ascending order

  let count = 0; // Counter to keep track of the frequency of each element
  let candidate = arr[0]; // Initiate variable to store our potential solution
  
  for(let i = 0; i < arr.length; i++) {
    if(arr[i] === candidate) {
      count++;
      if(count === k) {
        return candidate;
      }
    } else {
      candidate = arr[i];
      count = 1;
    }
  }
  
  return -1; // If the kth least common element does not exist in array, return -1
}
605 chars
21 lines

The kthLeastCommonElement function takes two arguments: an array arr and a number k. We sort the array in ascending order using the sort() method. We then iterate over the sorted array, counting the frequency of each element using a counter variable (count) and a candidate variable (candidate) to store our potential solution.

If the frequency of the current element equals k, we return candidate. Otherwise, we update candidate to the next element in the sorted array and reset count to 1. If the kth least common element does not exist in the array, we return -1.

To test our function, we can call it with an array and k value:

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

console.log(kthLeastCommonElement(arr, k)); // Output: 2
112 chars
5 lines

In this example, the 2nd least common element in the array [1, 2, 3, 4, 4, 4, 4, 5, 5] is 2. Thus, our function correctly returns 2.

gistlibby LogSnag