Advertisement

Most Common Word - LeetCode 819 Solution

Most Common Word - Complete Solution Guide

Most Common Word is LeetCode problem 819, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given a string paragraph and a string array of the banned words banned , 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 that words can not contain punctuation symbols. Example 1: Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"] Output: "ball" Explanation:

Detailed Explanation

The problem requires finding the most frequent word in a given paragraph that is not in a provided list of banned words. The search should be case-insensitive, and punctuation should be ignored. The output must be the most frequent *non-banned* word in lowercase. It's guaranteed there is at least one valid word and that the answer is unique. The input is a string `paragraph` and a string array `banned`. The output is a string: the most frequent non-banned word.

Solution Approach

The solution involves first preprocessing the paragraph by converting it to lowercase and splitting it into words, removing any punctuation marks. Then, it creates a set of banned words for efficient lookup. It iterates through the extracted words, counts their occurrences, and ignores banned words. Finally, it identifies the most frequent word among the non-banned words.

Step-by-Step Algorithm

  1. Step 1: Convert the paragraph to lowercase.
  2. Step 2: Remove punctuation from the paragraph and split it into words.
  3. Step 3: Create a set from the banned words array for O(1) lookup.
  4. Step 4: Iterate through the extracted words, and for each word, check if it's in the banned set.
  5. Step 5: If the word is not banned, increment its count in a word count map (or counter).
  6. Step 6: After iterating through all the words, find the word with the highest count in the word count map (or counter).
  7. Step 7: Return the word with the highest count.

Key Insights

  • Insight 1: Need to handle case-insensitivity by converting the paragraph to lowercase.
  • Insight 2: Need to remove punctuation and split the paragraph into words.
  • Insight 3: Need to efficiently check if a word is banned using a set data structure for O(1) lookup.

Complexity Analysis

Time Complexity: O(n+b)

Space Complexity: O(n+b)

Topics

This problem involves: Array, Hash Table, String, Counting.

Companies

Asked at: Datadog.