Python 0819.py
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
for c in "!?',;.":
paragraph = paragraph.replace(c, " ")
paragraph = paragraph.replace(" ", " ")
words = defaultdict(int)
for w in paragraph.split():
words[w.lower()] += 1
for b in banned:
if b.lower() in words:
del words[b.lower()]
high = max(words.values())
for w in words:
if words[w] == high:
return w
Difficulty
and has an acceptance rate of about 45% (900k+ submissions).
Typical patterns to solve this problem:
- Array
- Counting
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of finding the most frequent word in a text while ignoring a set of banned words. It proceeds by normalizing the input, counting occurrences in a case-insensitive manner, discarding any banned entries, and finally selecting the word with the highest frequency. The flow is linear with respect to the length of the paragraph and the size of the banned list.
Key Steps
Normalization of punctuation
The code first replaces a fixed collection of punctuation characters with spaces, ensuring that words adjacent to punctuation are separated correctly.
for c in "!?',;.":
paragraph = paragraph.replace(c, " ")
paragraph = paragraph.replace(" ", " ")
By converting punctuation to spaces, the subsequent split operation can treat them uniformly as delimiters. The extra replacement of a double space handles the case where two punctuation marks appear consecutively, preventing the creation of empty tokens.
Building a case-insensitive frequency map
A defaultdict of integers is used to tally each word after converting it to lower case.
words = defaultdict(int)
for w in paragraph.split():
words[w.lower()] += 1
The split() call respects any amount of whitespace, so any number of spaces introduced by the previous step are collapsed automatically. Lower-casing guarantees that “Word”, “word”, and “WORD” are counted together.
Removing banned words
Each entry from the banned list is examined in lower case; if it exists in the frequency map, it is deleted.
for b in banned:
if b.lower() in words:
del words[b.lower()]
This step ensures that banned words never influence the final selection, even if they appear many times in the paragraph. The check for existence before deletion avoids a potential KeyError.
Selecting the most frequent word
The maximum frequency value is obtained, and then the map is scanned to return the word that matches this count.
high = max(words.values())
for w in words:
if words[w] == high:
return w
Because the problem guarantees a unique answer, the first word encountered with the highest count is the correct result. The early return stops further iteration once the answer is found.
Edge Cases Handled
The normalization loop treats any of the listed punctuation characters uniformly, so inputs such as “Hello!!! World??” are reduced to “Hello World ” and subsequently split correctly. The additional replacement of double spaces covers scenarios where punctuation characters appear back-to-back, preventing empty strings from entering the word list.
Case insensitivity is addressed at both counting and banned-word removal stages, allowing inputs like “Bob” and a banned entry “bob” to be matched reliably.
If the banned list is empty, the removal loop simply performs no deletions, leaving the full frequency map intact. Conversely, if every word in the paragraph is banned, the map becomes empty; however, the problem constraints guarantee at least one non-banned word, so the max call always has a valid argument.
Multiple consecutive whitespace characters, whether introduced by punctuation replacement or present in the original paragraph, are collapsed by split(), ensuring that no empty tokens are counted.
Performance Optimizations
Using defaultdict(int) eliminates the need for explicit existence checks before incrementing a count, streamlining the counting loop. The replacement of punctuation characters in a tight for loop avoids the overhead of building a translation table, which would require additional data structures.
The extraction of the maximum frequency via max(words.values()) is performed once, rather than recomputing it during each iteration. The subsequent scan stops immediately after finding a matching word, avoiding unnecessary traversal of the entire dictionary when the answer appears early.
Overall, the algorithm maintains a straightforward linear progression through the data, leveraging built-in Python operations that are implemented in C for speed, such as str.replace, str.split, and dictionary lookups.
ELI5 - Simplified Explanation
Imagine that a whole book is written on a big piece of paper, but someone accidentally spilled some messy punctuation marks like commas and periods all over the words. To make sense of the story, the computer first goes through the text and carefully swaps every messy mark for a tiny space. This makes all the words stand out clearly so they can be identified.
Next, a special box is prepared to keep track of every word. As the computer reads each word, it puts a mark in the box to count how many times that exact word appears. Some words might appear just once, while others might pop up many times.
There is also a separate list of words that are not allowed, like a playground rule against saying certain things. The computer checks the big counting box and removes any word that is on the forbidden list. Even if a bad word was used a hundred times, it gets thrown away completely.
Finally, the computer looks at all the remaining words in the box and spots which one has the highest count. It picks that most frequent word as the winner from the entire paragraph. Every other word is left behind, and the winner is announced.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| pruthvikp | Python | |||||||||
| qiyuangong | Java | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| pruthvikp | Python | |||||||||
| qiyuangong | Java | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 521: Longest Uncommon Subsequence I
- problem 557: Reverse Words in a String III
- problem 697: Degree of an Array
- problem 771: Jewels and Stones
- problem 1700: Number of Students Unable to Eat Lunch
- problem 2073: Time Needed to Buy Tickets
- problem 399: Evaluate Division
- problem 435: Non-overlapping Intervals
- problem 547: Number of Provinces
- problem 841: Keys and Rooms
- problem 1466: Reorder Routes to Make All Paths Lead to the City Zero
- problem 2462: Total Cost to Hire K Workers
- problem 2542: Maximum Subsequence Score
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality