To find the kth most common element in an array, we need to first count the frequency of each element in the array. Once we have the frequency of each element, we need to sort the frequencies in descending order and return the kth frequency.
Here's the code that implements this:
index.tsx538 chars18 lines
Here's an example usage of the function:
index.tsx97 chars3 lines
In this example, the 2nd most common element in the array [1, 2, 2, 3, 4, 4, 4, 5, 5]
is 3
. The output of the function call kthMostCommonElement(arr, 2)
is 3
.
gistlibby LogSnag