Given a string paragraph and a list of banned words, return the most frequent word that is not banned. Words are case-insensitive and punctuation should be ignored. The answer is guaranteed to be unique.
This is a classic hash map frequency problem with string preprocessing. First normalize the paragraph: convert to lowercase and replace all punctuation with spaces. Split the result into words, ignoring empty strings. Build a hash map counting each word, skipping any word in the banned set. Track the word with the highest count as you go.
The hash map provides O(1) updates and lookups, making the entire process O(n + m) where n is the paragraph length and m is the number of banned words. The banned words are stored in a hash set for O(1) exclusion checks.
Edge cases include an empty paragraph (return empty string), a paragraph with only banned words (return empty string though the problem guarantees at least one non-banned word), and punctuation-heavy text like "a,b,c" where commas must be treated as separators.
The regex [^a-z]+ matches any sequence of non-letter characters. Replacing them with spaces converts punctuation, numbers, and whitespace into uniform separators. The split then produces clean word tokens. Using a hash set for banned words ensures O(1) exclusion checks during frequency counting.
Example Input & Output
Punctuation removed, single word a.
a is banned, b appears twice.
ball appears twice, hit is banned.
abc banned, def once.
Punctuation splits into a,b,c; b banned; a first.
Algorithm Flow
Solution Approach
Find the most frequently occurring word in a paragraph that is not in a banned list. First normalize the paragraph by converting to lowercase and splitting on non-letter characters. Count word frequencies using a hash map, skipping any word in the banned set. Track the word with the highest frequency.
The regex /[^a-z]+/ splits on any non-letter sequence, handling punctuation and spaces. The banned set provides O(1) lookup for filtering. Word counts are accumulated and the current leader is tracked during iteration to avoid a second pass.
Time complexity is O(n + m), space complexity is O(n + m).
Best Answers
import java.util.*;
class Solution {
public String solution(String paragraph, String[] banned) {
String normalized = paragraph.toLowerCase().replaceAll("[^a-z]+", " ");
String[] words = normalized.split(" ");
Set<String> bannedSet = new HashSet<>(Arrays.asList(banned));
Map<String,Integer> freq = new HashMap<>();
String best = "";
int bestCount = 0;
for (String w : words) {
if (w.isEmpty() || bannedSet.contains(w)) continue;
int c = freq.getOrDefault(w, 0) + 1;
freq.put(w, c);
if (c > bestCount) { bestCount = c; best = w; }
}
return best;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
