find the kth least frequent element in an array in ruby

To find the kth least frequent element in an array in Ruby, we can use a hash to count the frequency of each element, sort the hash by its values, and return the kth key in the sorted hash.

Here's the code:

main.rb
def kth_least_frequent(arr, k)
  freq = Hash.new(0)
  arr.each { |element| freq[element] += 1 }
  sorted_freq = freq.sort_by { |k, v| v }
  sorted_freq[k-1][0]
end

# example usage
arr = [1, 2, 3, 2, 4, 1, 3]
k = 2
puts kth_least_frequent(arr, k) # prints 4
258 chars
12 lines

In this code, we first create a hash "freq" to store the frequency of each element in the array. We iterate through the array and increment the value of the corresponding element key in the hash.

Next, we sort the hash by its values (i.e., by the frequency of each element), and store the sorted hash in "sorted_freq".

Finally, we return the kth least frequent element by accessing the (k-1)th element in the sorted hash (since the first element has index 0), and returning its key (i.e., the actual element value).

gistlibby LogSnag