You are given a piece of text, paragraph, and a list of words you must ignore, banned. Find the word that appears most often in the text, not counting banned words.
Capital letters do not matter, so Tree and tree are the same word, and the answer is returned in lower case. Punctuation is not part of any word: it only separates words, just like a space. There is always exactly one word that wins.
Example 1
Input: paragraph = "Cats nap; dogs nap. Cats PLAY, cats nap!", banned = ["nap"] Output: "cats" Why: cats appears 3 times; nap also does, but it is banned
2 more examples and the constraints
Example 2
Input: paragraph = "Go!", banned = [] Output: "go" Why: the only word, in lower case, without the !
Example 3
Input: paragraph = "red,blue,BLUE;red.blue", banned = [] Output: "blue" Why: punctuation splits words too: blue 3 times, red 2
Constraints
- 1 ≤ length of paragraph ≤ 1,000
- paragraph holds English letters, spaces and the symbols ! ? ' , ; .
- 0 ≤ length of banned ≤ 100
- Each banned word is 1 to 10 lower-case letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Rescan for every wordO(w²)
- Hash map countO(n + b)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 1,000-character paragraph | Verdict |
|---|---|---|---|
| Rescan for every word | O(w²) | Correct; repeats work | |
| Hash map count | O(n + b) | Best; one pass |
n = paragraph length, b = total length of banned words, w = number of words, L = word length.
Edge cases to test
- Punctuation with no space.
red,blueis two words, not one. - Capitals.
BLUEandbluecount together, and the answer is lower case. - A single word.
Go!givesgo. - Banned word is the most frequent. It is skipped, so the runner-up wins.
- Apostrophes.
it'ssplits intoitands, since the apostrophe is not a letter.
Common mistakes
- Splitting on spaces only, so
ball,andballbecome different words. - Comparing banned words before lower-casing, so
Hitslips past a ban onhit. - Counting the empty strings left between two separators as a word.
How to talk through it
- 1Clarify. Which characters can appear? Is case ignored? Is the answer always unique?
- 2Clean first. Non-letters become spaces, letters become lower case. Now it is a plain list of words.
- 3Count with a map. Skip banned words with a set lookup, add 1 for the rest.
- 4Pick the leader. Scan the map for the largest count, or track it as you go.
- 5Test out loud. Try punctuation without spaces, mixed case and a banned word that is the most common.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?