Most Common Word — LeetCode 819 Python Solution
- Problem
- #819
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.