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
.
Input:
words = ["hello", "world", "leetcode"]
ch = 'o'
Output:
["hello", "world"]
Q: Is the input list words
guaranteed to be non-empty?
A: Yes, you can assume the list words
is non-empty.
Q: Can the character ch
be a special character or a number?
A: Yes, the character ch
can be any valid character.
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.
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.
ch
.words
.ch
is present in the word.ch
is found in the word, append the word to the result list.ch
.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))
words
, which takes O(n) where n
is the number of words.m
is the length of the word.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.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?