find the kth most common element in an array in python

To find the kth most common element in an array, one approach is to use a dictionary to count the occurrences of each element in the array. Once we have the counts, we can sort the dictionary items by their values (i.e., the counts), and return the key (the element) at the kth position in the sorted list.

Here's the code:

main.py
def kth_most_common(arr, k):
    # create a dictionary to count the occurrences of elements in the array
    counts = {}
    for elem in arr:
        if elem in counts:
            counts[elem] += 1
        else:
            counts[elem] = 1

    # sort the dictionary items by value (i.e., the counts)
    sorted_counts = sorted(counts.items(), key=lambda x: x[1], reverse=True)

    # return the key (the element) at the kth position in the sorted list
    return sorted_counts[k-1][0]
488 chars
15 lines

This function takes an array arr and an integer k as input, and returns the kth most common element in arr. Note that if k is larger than the number of distinct elements in arr, the function will raise an IndexError.

gistlibby LogSnag