find the kth most frequent element in an array in python

To find the kth most frequent element in an array in Python, we can use a combination of dictionary and sorting.

The algorithm to achieve this goes as follows:

  1. Initialize an empty dictionary to keep track of the frequency of each element in the array.
  2. Loop through the array and add each element to the dictionary with a frequency of 1 if it's not already in the dictionary. If it's already in the dictionary, increment its frequency by 1.
  3. Sort the dictionary in descending order based on the frequency of each element.
  4. Return the kth element in the sorted dictionary.

Here's the Python implementation of the above algorithm:

main.py
def kth_most_frequent(arr, k):
    freq_dict = {}
    for num in arr:
        if num in freq_dict:
            freq_dict[num] += 1
        else:
            freq_dict[num] = 1
    
    sorted_dict = dict(sorted(freq_dict.items(), key=lambda item: item[1], reverse=True))
    
    return list(sorted_dict.keys())[k-1]
317 chars
12 lines

Here, arr is the input array and k is the desired rank of the element. The freq_dict dictionary holds the frequency count of each element and sorted_dict dictionary is created by sorting the freq_dict in descending order based on the frequency of each element. The kth_most_frequent function returns the kth element in the sorted dictionary.

Note that if there are ties in frequency and the kth most frequent element is not unique, this algorithm will still return a correct answer but not necessarily the element that comes first among the tied elements.

gistlibby LogSnag