Drill

ProblemsPython › patterns

The most repeated word

mediumpatternsHash mapsStringsParsingPython

A support bot scans a ticket and routes it via the word that shows up most, so the right team gets it.

most_common_word(text: string) → string

Solve it in the editor →

Where you start

def most_common_word(text: str) -> str:
    

Worked examples

CallResult
most_common_word("a b a")"a"
most_common_word("the quick brown fox")"the"
most_common_word("Order! The order, please.")"order"
most_common_word("x y y x")"x"

Hint

Split into lowercase words, count each, and track the first position of each word for the tie-break.

Reference solution in Python
def most_common_word(text: str) -> str:
    words = []
    cur = ''
    for ch in text.lower():
        if 'a' <= ch <= 'z':
            cur += ch
        elif cur:
            words.append(cur)
            cur = ''
    if cur:
        words.append(cur)
    if not words:
        return ''
    count = {}
    first = {}
    for i, w in enumerate(words):
        count[w] = count.get(w, 0) + 1
        if w not in first:
            first[w] = i
    best = words[0]
    for w, c in count.items():
        if c > count[best] or (c == count[best] and first[w] < first[best]):
            best = w
    return best

The same problem in another language

More patterns problems in Python