Most Common Word — LeetCode 819 Python Solution

EasyArrayHash TableStringCounting
Problem
#819
Pattern
Hash Map
Reading time
2 min

The problem

Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.

Example

Input
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output
"ball"
Explanation
"hit" occurs 3 times, but it is a banned word.

Python solution

Python
class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        s = set(banned)
        p = Counter(re.findall('[a-z]+', paragraph.lower()))
        return next(word for word, _ in p.most_common() if word not in s)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 819. Most Common Word is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 819. Most Common Word?
LeetCode 819. Most Common Word is rated Easy on LeetCode.
What is the time complexity of LeetCode 819. Most Common Word?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 819. Most Common Word?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 819. Most Common Word cover?
LeetCode 819. Most Common Word is tagged Array, Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview