KatInterview

837. Most Common Word

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the most frequent word in a given paragraph that is not on a list of banned words. Key requirements are that the word matching should be case-insensitive, punctuation should be ignored, and the final result must be in lowercase. The problem guarantees a unique answer, which simplifies the logic as we don't need to handle ties.

Solution

Most Common Word in Python

import re
from collections import Counter

class Solution:
    def mostCommonWord(self, paragraph: str, banned: list[str]) -> str:
        # 1. Create a set of banned words for O(1) average time lookup.
        banned_set = set(banned)
        
        # 2. Find all word-like sequences (only letters) using regex, after converting to lowercase.
        words = re.findall(r'[a-z]+', paragraph.lower())
        
        # 3. Create a list of words that are not in the banned set.
        non_banned_words = []
        for word in words:
            if word not in banned_set:
                non_banned_words.append(word)
        
        # 4. Use collections.Counter to count the frequency of each word.
        #    It returns a dictionary-like object.
        if not non_banned_words:
            return "" # Should not happen based on problem constraints
            
        word_counts = Counter(non_banned_words)
        
        # 5. The most_common(1) method returns a list containing the single
        #    most common element and its count as a tuple.
        #    Example: [('ball', 2)]
        #    We extract the word from the tuple.
        return word_counts.most_common(1)[0][0]

Most Common Word in Java

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        // 1. Create a set of banned words for O(1) average time lookup.
        Set<String> bannedWords = new HashSet<>(Arrays.asList(banned));
        
        // 2. A map to store frequencies of non-banned words.
        Map<String, Integer> counts = new HashMap<>();
        
        // 3. Normalize the paragraph: replace non-alphabetic characters with a space,
        //    convert to lowercase, and split into words by one or more spaces.
        String[] words = paragraph.replaceAll("[^a-zA-Z]", " ").toLowerCase().split("\\s+");
        
        String result = "";
        int maxCount = 0;
        
        // 4. Iterate through the words to count frequencies and find the most common one.
        for (String word : words) {
            // Skip empty strings that might result from splitting.
            if (!word.isEmpty() && !bannedWords.contains(word)) {
                // Increment count for the current word.
                counts.put(word, counts.getOrDefault(word, 0) + 1);
                
                // If this word's count is the new maximum, update the result.
                if (counts.get(word) > maxCount) {
                    maxCount = counts.get(word);
                    result = word;
                }
            }
        }
        
        return result;
    }
}

Most Common Word in C++

class Solution {
public:
    string mostCommonWord(string paragraph, vector<string>& banned) {
        // Use an unordered_set for fast O(1) average time lookups of banned words.
        unordered_set<string> banned_set(banned.begin(), banned.end());
        
        // A map to store the frequency of each word.
        unordered_map<string, int> counts;
        
        // Normalize the paragraph: replace non-alphabetic characters with spaces
        // and convert to lowercase.
        for (char &c : paragraph) {
            if (isalpha(c)) {
                c = tolower(c);
            } else {
                c = ' ';
            }
        }
        
        // Use a stringstream to easily split the paragraph by spaces.
        stringstream ss(paragraph);
        string word;
        string result = "";
        int max_count = 0;
        
        // Process each word.
        while (ss >> word) {
            // If the word is not in the banned set...
            if (banned_set.find(word) == banned_set.end()) {
                // Increment its count.
                counts[word]++;
                // Check if this word is now the most frequent.
                if (counts[word] > max_count) {
                    max_count = counts[word];
                    result = word;
                }
            }
        }
        
        return result;
    }
};

Most Common Word in TypeScript

function mostCommonWord(paragraph: string, banned: string[]): string {
    // 1. Create a set of banned words for efficient O(1) average time lookup.
    const bannedSet = new Set(banned);
    
    // 2. Normalize the paragraph to lowercase and extract all words.
    //    The regex /[a-z]+/g finds all sequences of one or more letters.
    //    'g' flag ensures all matches are found.
    //    The '|| []' handles the case where no words are found, preventing errors.
    const words = paragraph.toLowerCase().match(/[a-z]+/g) || [];
    
    // 3. A map to store the frequency of each non-banned word.
    const counts = new Map<string, number>();
    
    let result = "";
    let maxCount = 0;
    
    // 4. Iterate through the words to count frequencies and find the most common.
    for (const word of words) {
        if (!bannedSet.has(word)) {
            const newCount = (counts.get(word) || 0) + 1;
            counts.set(word, newCount);
            
            if (newCount > maxCount) {
                maxCount = newCount;
                result = word;
            }
        }
    }
    
    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.