Drill

ProblemsJava › patterns

The most repeated word

mediumpatternsHash mapsStringsParsingJava

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

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.

Solve it in Python →

Where you start

String mostCommonWord(String text) {
    
}

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

The same problem in another language

More patterns problems in Java