Drill

ProblemsTypeScript › patterns

The most repeated word

mediumpatternsHash mapsStringsParsingTypeScript

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

Solve it in the editor →

Where you start

function mostCommonWord(text: string): string {
  
}

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

The same problem in another language

More patterns problems in TypeScript