Similar Problems

Similar Problems not available

Count Words Obtained After Adding A Letter - Leetcode Solution

Companies:

LeetCode:  Count Words Obtained After Adding A Letter Leetcode Solution

Difficulty: Medium

Topics: hash-table string array sorting bit-manipulation  

Problem: Given a string s and a letter ch, return the number of words in s that contain at least one occurrence of ch.

Solution:

Approach 1: Brute Force

One approach to solve this problem is to iterate over all possible substrings of s and check whether the letter ch is present in each substring or not. If it is present in a substring, we can consider it as a valid word. We can count the number of valid words and return it as the answer. However, this approach has a time complexity of O(n^3) which is not efficient for large inputs.

Approach 2: Using Sets

Another approach is to use sets. We can create a set of all words in s and then iterate over this set to check whether each word contains ch or not. If a word contains ch, we can count it as a valid word. This approach has a time complexity of O(n * m) where n is the number of words in s and m is the maximum length of a word in s. It is more efficient than the previous approach.

Here is the Python code for this approach:

def countWords(s: str, ch: str) -> int: # Split the string into words words = s.split()

# Create a set of all words
words_set = set(words)

# Initialize a count variable
count = 0

# Iterate over the set of words
for word in words_set:
    if ch in word:
        count += 1

return count

This code first splits the input string s into words using the split function. It then creates a set of all words using the set function. It initializes a count variable to 0 and then iterates over the set of words. For each word in the set, it checks whether the letter ch is present using the in operator. If it is present, it increments the count variable. Finally, it returns the count variable as the answer.

Conclusion:

In this problem, we learned about two approaches to count the number of words that contain at least one occurrence of a given letter. The first approach was a brute force approach that had a time complexity of O(n^3) and was not efficient for large inputs. The second approach used sets and had a time complexity of O(n * m) which was more efficient. We implemented the second approach using Python.

Count Words Obtained After Adding A Letter Solution Code

1