LeetCode 819: Most Common Word Solution

Master LeetCode problem 819 (Most Common Word), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

819. Most Common Word

Problem Explanation

Explanation

To solve this problem, we can follow these steps:

  1. Preprocess the paragraph to extract words and convert them to lowercase.
  2. Create a set of banned words for efficient lookup.
  3. Count the frequency of each non-banned word using a hashmap.
  4. Find the word with the highest frequency that is not banned.

Time complexity: O(n) where n is the length of the paragraph Space complexity: O(n) for storing the word frequencies

Solution Code

import java.util.*;

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        Set<String> bannedSet = new HashSet<>(Arrays.asList(banned));
        Map<String, Integer> wordCount = new HashMap<>();
        
        String[] words = paragraph.toLowerCase().split("[^a-zA-Z]+");
        
        for (String word : words) {
            if (!bannedSet.contains(word)) {
                wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
            }
        }
        
        int maxCount = 0;
        String mostCommonWord = "";
        
        for (String word : wordCount.keySet()) {
            if (wordCount.get(word) > maxCount) {
                maxCount = wordCount.get(word);
                mostCommonWord = word;
            }
        }
        
        return mostCommonWord;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 819 (Most Common Word)?

This page provides optimized solutions for LeetCode problem 819 (Most Common Word) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 819 (Most Common Word)?

The time complexity for LeetCode 819 (Most Common Word) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 819 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 819 in Java, C++, or Python.

Back to LeetCode Solutions