Problems › TypeScript › patterns
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
Where you start
function mostCommonWord(text: string): string {
}
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 TypeScript
function mostCommonWord(text: string): string {
const words = text.toLowerCase().match(/[a-z]+/g) ?? [];
if (words.length === 0) return '';
const count = new Map<string, number>();
const first = new Map<string, number>();
for (let i = 0; i < words.length; i++) {
count.set(words[i], (count.get(words[i]) ?? 0) + 1);
if (!first.has(words[i])) first.set(words[i], i);
}
let best = words[0];
for (const [w, c] of count) {
if (c > count.get(best)! || (c === count.get(best)! && first.get(w)! < first.get(best)!)) best = w;
}
return best;
}