Python problem 8 of 30

Most common character

  • Python
  • Easy

Write most_common_char(s) that returns the character appearing most often in a non-empty string. If there is a tie, return the one that appears first in the string.

most_common_char("banana")   # "a"
most_common_char("abba")     # "a"
Show hint

Count first, then walk the original string from the left to settle ties.

Show solution
from collections import Counter

def most_common_char(s):
    counts = Counter(s)
    best = max(counts.values())
    for ch in s:
        if counts[ch] == best:
            return ch

Counter builds the counts in one pass. Scanning s from the left then finds the first character with the top count, which handles ties correctly. O(n) time.

Want a problem like this every day? See today's problem and keep a streak going.