#819

Most Common Word

Easy
ArrayHash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

This approach uses a hash map to count the occurrences of each word efficiently. By using a set for banned words, we can quickly check if a word is banned. This significantly reduces the time complexity.

⚙️

Algorithm

5 steps
  1. 1Step 1: Convert the paragraph to lowercase and extract words using regex to ignore punctuation.
  2. 2Step 2: Store banned words in a set for O(1) lookup.
  3. 3Step 3: Use a hash map to count occurrences of each word that is not banned.
  4. 4Step 4: Iterate through the hash map to find the word with the highest count.
  5. 5Step 5: Return that word.
solution.py15 lines
1# Full working Python code
2import re
3
4
5def most_common_word(paragraph, banned):
6    words = re.findall(r'\w+', paragraph.lower())
7    banned_set = set(banned)
8    count = {}
9    for word in words:
10        if word not in banned_set:
11            count[word] = count.get(word, 0) + 1
12    return max(count, key=count.get)
13
14# Example usage
15print(most_common_word("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]))

Complexity note: The time complexity is O(n) because we traverse the paragraph once to count the words, and the space complexity is O(n) due to the storage of the word counts.

  • 1Words are case-insensitive and punctuation should be ignored.
  • 2Using a hash map allows for efficient counting and retrieval of the most common word.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.