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.ts605 chars21 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.ts112 chars5 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