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
Java 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
String mostCommonWord(String text) {
}
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 Java
String mostCommonWord(String text) {
List<String> words = new ArrayList<>();
StringBuilder cur = new StringBuilder();
for (char ch : text.toLowerCase().toCharArray()) {
if (ch >= 'a' && ch <= 'z') cur.append(ch);
else if (cur.length() > 0) { words.add(cur.toString()); cur.setLength(0); }
}
if (cur.length() > 0) words.add(cur.toString());
if (words.isEmpty()) return "";
Map<String, Integer> count = new HashMap<>();
Map<String, Integer> first = new HashMap<>();
for (int i = 0; i < words.size(); i++) {
String w = words.get(i);
count.put(w, count.getOrDefault(w, 0) + 1);
if (!first.containsKey(w)) first.put(w, i);
}
String best = words.get(0);
for (Map.Entry<String, Integer> e : count.entrySet()) {
String w = e.getKey();
int c = e.getValue();
if (c > count.get(best) || (c == count.get(best) && first.get(w) < first.get(best))) best = w;
}
return best;
}