find the kth most common element in an array in go

Here's an implementation that uses counting and sorting:

main.go
func KthMostCommonElement(arr []int, k int) int {
    count := make(map[int]int)
    for _, num := range arr {
        count[num]++
    }

    pairs := make([][2]int, 0, len(count))
    for num, freq := range count {
        pairs = append(pairs, [2]int{num, freq})
    }

    sort.Slice(pairs, func(i, j int) bool {
        return pairs[i][1] > pairs[j][1]
    })

    return pairs[k-1][0]
}
393 chars
18 lines

The function KthMostCommonElement takes an array of integers arr and an integer k, and returns the kth most common element in the array. We first count the frequency of each element in the array using a map count, and then convert the map into a slice of pairs (element, frequency). We sort this slice by decreasing frequency using sort.Slice. Finally, we return the number of the kth element in the sorted slice. Note that if there are ties for the kth most common element, this implementation will return one of the tied elements arbitrarily.

gistlibby LogSnag