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
C++ 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
std::string mostCommonWord(std::string text) {
}
Worked examples
| Call | Result |
|---|---|
mostCommonWord(std::string("a b a")) | std::string("a") |
mostCommonWord(std::string("the quick brown fox")) | std::string("the") |
mostCommonWord(std::string("Order! The order, please.")) | std::string("order") |
mostCommonWord(std::string("x y y x")) | std::string("x") |
Hint
Split into lowercase words, count each, and track the first position of each word for the tie-break.
Reference solution in C++
std::string mostCommonWord(std::string text) {
std::vector<string> words;
string cur;
for (char ch : text) {
if (ch >= 'A' && ch <= 'Z') ch += 32;
if (ch >= 'a' && ch <= 'z') cur += ch;
else if (!cur.empty()) { words.push_back(cur); cur.clear(); }
}
if (!cur.empty()) words.push_back(cur);
if (words.empty()) return "";
std::map<string, int> count, first;
for (size_t i = 0; i < words.size(); i++) {
count[words[i]]++;
if (first.count(words[i]) == 0) first[words[i]] = (int) i;
}
string best = words[0];
for (auto& e : count) {
string w = e.first;
int c = e.second;
if (c > count[best] || (c == count[best] && first[w] < first[best])) best = w;
}
return best;
}