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

Number: 3194

Difficulty: Easy

Paid? No

Companies: Amazon, Deliveroo


Problem Description

Given a 0-indexed array of strings words and a lowercase English character x, return an array of indices representing the words that contain the character x. The indices can be returned in any order.


Key Insights

  • Iterate over the list of words while keeping track of each word's index.
  • For each word, check if the character x exists in that word.
  • If the character is found, add the corresponding index to the result list.
  • Return the final list of indices where the word contains the character x.
  • Edge case: If no words contain the character, return an empty array.

Space and Time Complexity

Time Complexity: O(n * m), where n is the number of words and m is the average length of each word. Space Complexity: O(n) in the worst case (if every word contains x, we store every index).


Solution

We use a linear scan over the list of words. For each word, we check the presence of the target character using an efficient string operation (like the "in" operator in Python, "includes" in JavaScript, or "indexOf" in Java). Since words are small (1 <= length <= 50) and there are at most 50 words, this approach is efficient. The main data structure used is a simple list (or vector/array) to store the resulting indices. The algorithm leverages basic string searching which is straightforward given the problem constraints.


Code Solutions

def find_words_containing_character(words, x):
    result = []
    # Iterate through each word with its index.
    for index, word in enumerate(words):
        # If the character x is in the word, add the index to the result.
        if x in word:
            result.append(index)
    return result

# Example usage:
words = ["abc", "bcd", "aaaa", "cbc"]
x = "a"
print(find_words_containing_character(words, x))  # Expected output: [0, 2]
← Back to All Questions