The most repeated word
A support bot scans a ticket and routes it via the word that shows up most, so the right team gets it.
- A word is a run of letters; numbers, punctuation and whitespace split words and are ignored.
- Comparison is case-insensitive: “Order” and “order” are the same word.
- If several words tie on count, return the one that appeared first overall.
- No words at all gives an empty string.
most_common_word(text: string) → string
Where you start
def most_common_word(text: str) -> str:
Worked examples
| Call | Result |
|---|---|
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