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.go441 chars20 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