find the kth least common element in an array in go

To find the kth least common element in an array, we can first sort the array in ascending order. Then, we can traverse the sorted array and keep track of the count of unique elements seen so far. Once we reach the kth unique element, we can return it.

Here's an example implementation in Go:

main.go
func findKthLeastCommonElement(arr []int, k int) int {
    counts := make(map[int]int)
    for _, num := range arr {
        counts[num]++
    }
    
    uniqueElems := make([]int, 0, len(counts))
    for num, count := range counts {
        if count == 1 {
            uniqueElems = append(uniqueElems, num)
        }
    }
    
    sort.Ints(uniqueElems)
    if k > len(uniqueElems) {
        return -1
    }
    return uniqueElems[k-1]
}
441 chars
20 lines

We first use a map to count the occurrence of each element in the array. Then, we loop through the map and add each unique element to a slice. The sort function is used to sort the unique elements in ascending order.

Finally, we check if k is greater than the number of unique elements. If it is, we return -1 to indicate that the kth least common element does not exist. Otherwise, we return the kth least common element from the sorted unique elements slice.

gistlibby LogSnag