Skip to content
Problem 819 · LeetCode 819(opens in a new tab)

Most Common Word

EasyHash tables

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.

Try it on LeetCode(opens in a new tab)
  1. Rescan for every wordO(w²)
  2. Hash map countO(n + b)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 1,000-character paragraphVerdict
Rescan for every wordO(w²)
Correct; repeats work
Hash map countO(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,blue is two words, not one.
  • Capitals. BLUE and blue count together, and the answer is lower case.
  • A single word. Go! gives go.
  • Banned word is the most frequent. It is skipped, so the runner-up wins.
  • Apostrophes. it's splits into it and s, since the apostrophe is not a letter.

Common mistakes

  • Splitting on spaces only, so ball, and ball become different words.
  • Comparing banned words before lower-casing, so Hit slips past a ban on hit.
  • Counting the empty strings left between two separators as a word.

How to talk through it

  1. 1Clarify. Which characters can appear? Is case ignored? Is the answer always unique?
  2. 2Clean first. Non-letters become spaces, letters become lower case. Now it is a plain list of words.
  3. 3Count with a map. Skip banned words with a set lookup, add 1 for the rest.
  4. 4Pick the leader. Scan the map for the largest count, or track it as you go.
  5. 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?