Drill

ProblemsGo › patterns

The most repeated word

mediumpatternsHash mapsStringsParsingGo

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

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.

Solve it in Python →

Where you start

func mostCommonWord(text string) string {
	
}

Worked examples

CallResult
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
}

The same problem in another language

More patterns problems in Go