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.rb363 chars12 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.rb97 chars5 lines
This example array has four unique elements, and their frequency counts are:
main.rb20 chars5 lines
Sorting these keys by frequency results in [4, 3, 2, 1]
, so the second most common element is 3.
gistlibby LogSnag