find the kth most frequent element in an array in go

To find the kth most frequent element in an array, one approach is to use a map to keep track of the frequency of each element in the array. Then, we can sort the elements of the map based on their frequency and return the kth element. Alternatively, we can use a max-heap to keep track of the k most frequent elements in the array.

Here is an implementation using a map and sorting:

main.go
func kthMostFrequent(arr []int, k int) int {
    // create a map to store the frequency of each element in the array
    freq := make(map[int]int)
    for _, num := range arr {
        freq[num]++
    }
    
    // create a slice to store the frequency of each unique element in the array
    uniqueFreqs := make([]int, 0, len(freq))
    for _, f := range freq {
        uniqueFreqs = append(uniqueFreqs, f)
    }
    
    // sort the unique frequency slice in descending order
    sort.Sort(sort.Reverse(sort.IntSlice(uniqueFreqs)))
    
    // return the kth most frequent element
    for num, f := range freq {
        if f == uniqueFreqs[k-1] {
            return num
        }
    }
    
    // if k is larger than the number of unique elements in the array, return -1
    return -1
}
790 chars
27 lines

And here is an implementation using a max-heap:

main.go
func kthMostFrequent(arr []int, k int) int {
    // create a map to store the frequency of each element in the array
    freq := make(map[int]int)
    for _, num := range arr {
        freq[num]++
    }
    
    // create a max heap to store the k most frequent elements in the array
    hp := &maxHeap{}
    heap.Init(hp)
    for num, f := range freq {
        heap.Push(hp, item{num, f})
        if hp.Len() > k {
            heap.Pop(hp)
        }
    }
    
    // return the kth most frequent element
    if hp.Len() == k {
        return (*hp)[0].value
    }
    
    // if k is larger than the number of unique elements in the array, return -1
    return -1
}

type item struct {
    value int
    priority int
}

type maxHeap []item

func (h maxHeap) Len() int           { return len(h) }
func (h maxHeap) Less(i, j int) bool { return h[i].priority > h[j].priority }
func (h maxHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *maxHeap) Push(x interface{}) {
    *h = append(*h, x.(item))
}

func (h *maxHeap) Pop() interface{} {
    old := *h
    n := len(old)
    x := old[n-1]
    *h = old[0 : n-1]
    return x
}
1139 chars
49 lines

related categories

gistlibby LogSnag