Most Common Word (LeetCode 819): Solution and Explanation

Easy
Array
Hash Table
String
Counting

You get a paragraph of text and a list of banned words. Return the most frequent word that is not banned, in lowercase, ignoring case and punctuation.

Intuition

The hard part is not counting, it is deciding what a word is. Capital letters and punctuation make the same word look different: Ball, ball, and BALL should all count as ball.

Once you lowercase everything and treat every non-letter as a space, the paragraph becomes a clean list of words. From there it is an ordinary frequency count.

Banned words simply never reach the counter. A hash set makes that check constant time, and tracking the leader while counting removes the need for a second pass over the map.

Approach: Normalize, filter, count

  1. Put the banned words in a hash set.
  2. Lowercase the paragraph, replace every non-letter with a space and split it into words.
  3. For each word that is not banned, add 1 to its count in a hash map.
  4. Whenever a word's count is larger than the best count so far, make it the new leader.
  5. Return the leader after the last word.

Step-by-step example

paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
  1. The banned set is {hit}. After normalizing, the words are bob, hit, a, ball, the, hit, ball, flew, far, after, it, was, hit.
  2. bob gets count 1 and becomes the leader. hit is banned and skipped. a and ball reach 1 but do not beat bob.
  3. the reaches 1, hit is skipped again, and ball reaches 2, which beats bob's 1, so ball takes the lead.
  4. flew, far, after, it and was each reach 1, and the final hit is skipped.
  5. No word passes 2, so the answer is "ball".

Code: Python, Java, C++

1class Solution:
2    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
3        banned_set = set(banned)
4        words = "".join(c if c.isalpha() else " " for c in paragraph.lower()).split()
5        count = {}
6        best, best_count = "", 0
7        for w in words:
8            if w in banned_set:
9                continue
10            count[w] = count.get(w, 0) + 1
11            if count[w] > best_count:
12                best, best_count = w, count[w]
13        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + b)

Normalizing and splitting touch each of the n paragraph characters once, each word costs O(1) average for the set and map lookups, and building the set costs b for the banned words.

Space

O(n + b)

The word list and the count map hold at most n characters, and the banned set holds b.

Other approaches

Character scan without splitting (time O(n + b), space O(n + b))

Walk the paragraph one character at a time, building the current word in a buffer and closing it on any non-letter. It avoids creating the intermediate word list but has the same complexity.

Count everything, then pick the max (time O(n + b), space O(n + b))

Count every allowed word first and take the key with the largest value in a second pass. It is equally correct and some find it easier to read, at the cost of a second loop over the map.

Common mistakes

  • Splitting only on spaces. Text like b,b,b has no spaces, so it would be read as one word instead of three.
  • Forgetting to lowercase before comparing with the banned list, which is given in lowercase.
  • Checking banned words with a list instead of a set, which turns each lookup into a linear scan.
  • In Java and JavaScript, a regex split can produce an empty first token when the paragraph starts with punctuation; skip empty strings.

Frequently asked questions

Why replace punctuation with spaces instead of deleting it?

Deleting would glue words together. In b,b,b the commas are the only separators, so removing them would leave the single word bbb.

What if two words tie for the highest count?

The problem guarantees the answer is unique, so a tie for first place cannot happen. Updating the leader only on a strictly larger count is enough.

Do I need a separate pass to find the maximum?

No. Keep the best word and its count as you go, and replace them whenever a word's new count is larger. The leader after the last word is the answer.

Is a regex required?

No. Any method that maps non-letters to separators works, including a manual character loop. Regex is just a short way to write it in Java and JavaScript.