LeetCode Solutions

819. Most Common Word

Time: $O(|\texttt{paragraph}|)$

Space: $O(|\texttt{paragraph}| + |\texttt{banned}|)$

			

class Solution {
 public:
  string mostCommonWord(string paragraph, vector<string>& banned) {
    string ans;
    int maxCount = 0;
    unordered_map<string, int> count;
    unordered_set<string> bannedSet{begin(banned), end(banned)};

    // Make paragraph to lowercase and empty punctuations
    for (char& c : paragraph)
      c = isalpha(c) ? tolower(c) : ' ';

    istringstream iss(paragraph);

    for (string word; iss >> word;)
      if (!bannedSet.count(word))
        ++count[word];

    for (const auto& [word, freq] : count)
      if (freq > maxCount) {
        maxCount = freq;
        ans = word;
      }

    return ans;
  }
};
			

class Solution {
  public String mostCommonWord(String paragraph, String[] banned) {
    Pair<String, Integer> ans = new Pair<>("", 0);
    Set<String> bannedSet = new HashSet<>(Arrays.asList(banned));
    Map<String, Integer> count = new HashMap<>();
    String[] words = paragraph.replaceAll("\\W+", " ").toLowerCase().split("\\s+");

    for (final String word : words)
      if (!bannedSet.contains(word)) {
        count.put(word, count.getOrDefault(word, 0) + 1);
        if (count.get(word) > ans.getValue())
          ans = new Pair<>(word, count.get(word));
      }

    return ans.getKey();
  }
}
			

class Solution:
  def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
    banned = set(banned)
    words = re.findall(r'\w+', paragraph.lower())
    return Counter(word for word in words if word not in banned).most_common(1)[0][0]