How to find the element with minimum occurrences in an array with Ruby

1 Answer

0 votes
# Finds the element with the minimum occurrences in an array.
#
# @param array [Array] The input array to process.
# @return [Object, nil] The least frequent element, or nil if array is empty.
def min_occurrence(array)
  return nil if array.nil? || array.empty?

  # 1. tally counts occurrences into a Hash: { 1=>3, 3=>4, 4=>3, 5=>2, 2=>3 } (Ruby 2.7+)
  # 2. min_by extracts the key-value pair [element, count] with the lowest count
  # 3. .first gets the element key from that tuple
  array.tally.min_by { |_element, count| count }&.first
end

# Example usage:
arr = [1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3]

result = min_occurrence(arr)

if result
  puts result # Output: 5
else
  puts 'The array was empty.'
end



# run:
#
# 5
#

 



answered Sep 26 by avibootz
...