Ruby Coding Interview Question: Most Common Character In The String
Question
Write a method in Ruby that takes a string as input and returns the most common character in the string. If there are multiple characters that occur with the same frequency, return the one that comes first in alphabetical order. The method should be named most_common_character
and should take one parameter, str
, which represents the input string.
most_common_character("abracadabra") # Output: "a"
most_common_character("hello world") # Output: "l"
Your solution should satisfy the following requirements:
- The method should be case-sensitive, treating uppercase and lowercase characters as distinct.
- If the input string is empty, the method should return
nil
.
Answer
Here’s a possible solution in Ruby
def most_common_character(str)
return nil if str.empty?
char_frequency = Hash.new(0)
str.each_char do |char|
char_frequency[char] += 1
end
max_frequency = char_frequency.values.max
most_common_chars = char_frequency.select { |_, freq| freq == max_frequency }.keys
most_common_chars.min
end
Explanation:
- We first handle the case where the input string is empty by returning
nil
.