Problem: Write a method that takes in a string. Your method should return the most common letter in the array, and a count of how many times it appears.
Note: I solved it with Ruby, but the solution will be almost the same with other OOP language which have arrays and hashes.
Solution:
Split the string into an array of its characters/letters.
Put each char in a hash as key and starting value = 1.
When you find a character again, increase its value by 1.
Iterate your hash to find the most common character.
My solution works, but, is there a simpler & better way to do it?
What are the disadvantages of my solution?
def most_common_letter(string)
hash = {}
arr = string.split("")
i = 0
ge = "" # the char which occurs the most times in string
max = 0 # number of times ge occurs in string
while i < arr.length
e = arr[i]
if hash.has_key? e
hash[e] += 1
else
hash[e] = 1
end
i = i + 1
end
# Find most common character
hash.each do |k,v|
if(v > max)
max = v
ge = k
end
end
return ge.to_s + ":" + max.to_s
end
#Test
puts most_common_letter("abca")
puts most_common_letter("g")