CodePark/ problems / Count Words
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Foundations

Count Words

easyabout 10 minutes in an interview

Write countWords(text) that returns a Map from each word in text to the number of times it appears.

  • A word is a run of letters a–z and digits 0–9. Everything else separates words: spaces, punctuation, apostrophes and line breaks. So "don't" counts as two words, "don" and "t".
  • Counting ignores case: "The" and "the" are the same word. Store keys in lowercase.
  • Keys must be in the order each word first appears in the text.
  • If there are no words, return an empty Map.

Tip: text.toLowerCase().match(/[a-z0-9]+/g) gives you an array of the words. It gives null when there are no words. You write the counting yourself.

Input: text = "Go, go, GO team!" Output: Map { "go" → 3, "team" → 1 }
Input: text = "The cat saw the other cat." Output: Map { "the" → 2, "cat" → 2, "saw" → 1, "other" → 1 }
Input: text = "...!" Output: Map {}