algoadvance

You are given a list of strings words and a single character ch. Your task is to find and return all the strings in the list words that contain the character ch.

Example:

Input:

words = ["hello", "world", "leetcode"]
ch = 'o'

Output:

["hello", "world"]

Clarifying Questions

  1. Q: Is the input list words guaranteed to be non-empty? A: Yes, you can assume the list words is non-empty.

  2. Q: Can the character ch be a special character or a number? A: Yes, the character ch can be any valid character.

  3. Q: What should be the case sensitivity for matching the character ch in the words? A: The matching should be case-sensitive, according to the given example.

  4. Q: Are there any constraints on the length of the list words or on the length of individual words? A: The problem statement does not specify constraints, but we’ll assume reasonable constraints suitable for typical coding challenges.

Strategy

  1. Initialization: Create an empty list to hold the words that contain the character ch.
  2. Iteration: Loop through each word in the list words.
  3. Containment Check: For each word, check if the character ch is present in the word.
  4. Appending: If the character ch is found in the word, append the word to the result list.
  5. Return the Result List: After checking all words, return the list of words containing the character ch.

Code

Here’s the Python code that implements the strategy described above:

def find_words_containing_char(words, ch):
    # Result list to hold words containing the character `ch`
    result = []
    
    # Iterate over each word in the input list
    for word in words:
        if ch in word:
            result.append(word)
    
    return result

# Example usage:
words = ["hello", "world", "leetcode"]
ch = 'o'
print(find_words_containing_char(words, ch))

Time Complexity

Combining these, the overall time complexity is O(n * m), where n is the number of words and m is the average length of the words.

Try our interview co-pilot at AlgoAdvance.com