We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find Words Containing Character

Difficulty: Easy


Problem Description

You are given a 0-indexed array of strings words and a character x. Return an array of indices representing the words that contain the character x. Note that the returned array may be in any order.


Key Insights

  • The task requires checking each word in the array to see if it contains the specified character x.
  • We need to return the indices of the words that contain x.
  • The problem can be efficiently solved by iterating through the list of words and using a simple membership check to see if x is in each word.

Space and Time Complexity

Time Complexity: O(n * m), where n is the number of words and m is the maximum length of a word (since we may check each character of each word).
Space Complexity: O(k), where k is the number of indices stored in the result array.


Solution

The algorithm involves iterating over the array of words and checking if the character x is present in each word. We can use a list to store the indices of the words that contain x. For each word, if x is found, we append the index of that word to our result list. Finally, we return the list of indices.


Code Solutions

def find_words_containing_character(words, x):
    result = []
    for index, word in enumerate(words):
        if x in word:  # Check if x is in the current word
            result.append(index)  # Add index to result if found
    return result
← Back to All Questions