Start the marathon: find the most common character in a string.
Count the occurrences of each character and then take the one with the highest count. The two steps are separate, which is the shape of most counting problems: build a summary with one pass, then answer the question from the summary.
from collections import Counter
def most_common_char(text):
counts = Counter(text)
return max(counts, key=counts.get)
print(most_common_char("interview"))
print(most_common_char("abc"))The outputs are i and a. In interview the letter i appears twice, and so does the letter e, but the i appears first in the string and the counts dictionary preserves insertion order, so the i is returned. In abc every letter appears once and the a is the first.
The mechanism is that the dictionary maps each character to its count, and the maximum is taken over those counts. Using the count as the key of the max function is what makes it pick the character rather than the number, and it is the step people most often get wrong by returning the count instead.
The trade-off to name is the tie. When two characters share the highest count, the answer depends on the order, and saying which convention you are using is part of a good answer. There is also the empty string to handle, since the max of an empty sequence raises an error. For a longer text the same pattern is the first half of the top k frequent elements problem, where the second half is selecting the k largest counts, and a heap or a bucket sort does that part.