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
public 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 C#
public string MostCommonWord(string text) {
var words = new List<string>();
var cur = new StringBuilder();
foreach (char ch in text.ToLowerInvariant()) {
if (ch >= 'a' && ch <= 'z') cur.Append(ch);
else if (cur.Length > 0) { words.Add(cur.ToString()); cur.Clear(); }
}
if (cur.Length > 0) words.Add(cur.ToString());
if (words.Count == 0) return "";
var count = new Dictionary<string, int>();
var first = new Dictionary<string, int>();
for (int i = 0; i < words.Count; i++) {
string w = words[i];
count[w] = count.GetValueOrDefault(w, 0) + 1;
if (!first.ContainsKey(w)) first[w] = i;
}
string best = words[0];
foreach (var e in count) {
string w = e.Key;
int c = e.Value;
if (c > count[best] || (c == count[best] && first[w] < first[best])) best = w;
}
return best;
}