Leetcode 819. Most Common Word
Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn’t banned, and that the answer is unique.
!?',;.
.paragraph
always a valid non-empty string?
banned
words always a non-empty list of strings?
HashMap
to count the occurrences of each word that is not banned.HashMap
to find the word with the highest frequency.import java.util.*;
public class MostCommonWord {
public String mostCommonWord(String paragraph, String[] banned) {
Set<String> bannedSet = new HashSet<>(Arrays.asList(banned));
Map<String, Integer> wordCount = new HashMap<>();
// Normalize the paragraph
String normalizedStr = paragraph.replaceAll("[!?',;\\.]", " ").toLowerCase();
String[] words = normalizedStr.split("\\s+");
// Count words that are not banned
for (String word : words) {
if (!bannedSet.contains(word)) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
}
// Find the most frequent word
String mostCommon = null;
int maxCount = 0;
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
if (entry.getValue() > maxCount) {
maxCount = entry.getValue();
mostCommon = entry.getKey();
}
}
return mostCommon;
}
public static void main(String[] args) {
MostCommonWord solution = new MostCommonWord();
String paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.";
String[] banned = {"hit"};
System.out.println(solution.mostCommonWord(paragraph, banned)); // Output: "ball"
}
}
HashMap
takes O(m), where m is the number of words in the paragraph.HashMap
entries takes O(k), where k is the number of unique words.Overall, the time complexity is O(n + m + k). Since m and k are bounded by n, the overall time complexity simplifies to O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?