find the kth most common element in an array in ruby

One approach to solve this problem is to first count the occurrences of each element in the array, then sort the array by frequency, and finally return the k-th element.

Here's an implementation in Ruby:

main.rb
def kth_most_common_element(array, k)
  # Step 1: Count the occurrences of each element
  counts = Hash.new(0)
  array.each {|element| counts[element] += 1}

  # Step 2: Sort the elements by frequency
  sorted_elements = counts.keys.sort_by {|element| -counts[element]}

  # Step 3: Return the k-th element, or nil if k is out of range
  sorted_elements[k-1]
end
363 chars
12 lines

In this implementation, we first create a hash counts that maps each element to its frequency using Array#each and Hash#[]=. Next, we sort the keys of counts by frequency using Enumerable#sort_by. Finally, we return the k-th element from the sorted array using Array#[], which returns nil if k is out of range.

Here's an example usage of the method:

main.rb
array = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
k = 2

puts kth_most_common_element(array, k) # Output: 3
97 chars
5 lines

This example array has four unique elements, and their frequency counts are:

main.rb
1: 1
2: 2
3: 3
4: 4
20 chars
5 lines

Sorting these keys by frequency results in [4, 3, 2, 1], so the second most common element is 3.

gistlibby LogSnag