Most Common Word - Problem

Given a string paragraph and a string array of the banned words, 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.

The words in paragraph are case-insensitive and the answer should be returned in lowercase.

Note: Words cannot contain punctuation symbols.

Input & Output

Example 1 — Basic Case
$ Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
💡 Note: "hit" appears 3 times but is banned. "ball" appears 2 times (case-insensitive: "ball", "BALL") and is not banned, making it the most frequent valid word.
Example 2 — Multiple Banned Words
$ Input: paragraph = "a, a, a, a, b,b,b,c, c", banned = ["a"]
Output: "b"
💡 Note: "a" appears 4 times but is banned. "b" appears 3 times and "c" appears 2 times. "b" is the most frequent non-banned word.
Example 3 — Case Insensitive
$ Input: paragraph = "Bob bob BOB", banned = []
Output: "bob"
💡 Note: "Bob", "bob", and "BOB" are the same word (case-insensitive). "bob" appears 3 times and no words are banned.

Constraints

  • 1 ≤ paragraph.length ≤ 1000
  • paragraph consists of English letters, space ' ', or one of the symbols: "!?',;."
  • 0 ≤ banned.length ≤ 100
  • 1 ≤ banned[i].length ≤ 10
  • banned[i] consists of only lowercase English letters

Visualization

Tap to expand
Most Common Word - Single Pass with Immediate Filtering INPUT paragraph: "Bob hit a ball, the hit BALL flew far after it was hit." Words Extracted: bob hit a ball the hit BALL banned[]: "hit" Valid word Banned Other ALGORITHM STEPS 1 Create banned Set O(1) lookup for filtering 2 Parse words (lowercase) Remove punctuation, normalize 3 Filter + Count in one pass Skip banned, update HashMap 4 Track max frequency Update result if count higher Word Frequency Map bob 1 ball 2 the 1 a:1 flew:1 far:1 after:1 it:1 was:1 FINAL RESULT Most frequent non-banned: "ball" Frequency: 2 Output: "ball" OK - Answer found! "hit" appears 3 times but is BANNED "ball" = next highest (2) Key Insight: Single Pass Efficiency: By combining word extraction, filtering, and counting in one pass through the string, we achieve O(n) time complexity. Using a HashSet for banned words enables O(1) lookup, and tracking the maximum frequency during iteration eliminates the need for a separate pass to find the most common word. TutorialsPoint - Most Common Word | Single Pass with Immediate Filtering
Asked in
Amazon 45 Apple 32 Google 28 Facebook 21
28.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen