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.
mostCommonWord(text: string) → string
Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
func mostCommonWord(text string) string {
}
Worked examples
| Call | Result |
|---|---|
mostCommonWord("a b a") | "a" |
mostCommonWord("the quick brown fox") | "the" |
mostCommonWord("Order! The order, please.") | "order" |
mostCommonWord("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 Go
func mostCommonWord(text string) string {
words := []string{}
cur := ""
for i := 0; i < len(text); i++ {
ch := text[i]
if ch >= 'A' && ch <= 'Z' {
ch += 32
}
if ch >= 'a' && ch <= 'z' {
cur += string(ch)
} else if cur != "" {
words = append(words, cur)
cur = ""
}
}
if cur != "" {
words = append(words, cur)
}
if len(words) == 0 {
return ""
}
count := map[string]int{}
first := map[string]int{}
for i, w := range words {
count[w]++
if _, ok := first[w]; !ok {
first[w] = i
}
}
best := words[0]
for w, c := range count {
if c > count[best] || (c == count[best] && first[w] < first[best]) {
best = w
}
}
return best
}