Find Words Containing Character
EasyUpdated: Aug 2, 2025
Practice on:
Problem
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.
Examples
Example 1:
Input: words = ["leet","code"], x = "e"
Output: [0,1]
Explanation: "e" occurs in both words: "l** _ee_** t", and "cod _**e**_ ". Hence, we return indices 0 and 1.
Example 2:
Input: words = ["abc","bcd","aaaa","cbc"], x = "a"
Output: [0,2]
Explanation: "a" occurs in "**_a_** bc", and "_**aaaa**_ ". Hence, we return indices 0 and 2.
Example 3:
Input: words = ["abc","bcd","aaaa","cbc"], x = "z"
Output: []
Explanation: "z" does not occur in any of the words. Hence, we return an empty array.
Constraints:
1 <= words.length <= 501 <= words[i].length <= 50xis a lowercase English letter.words[i]consists only of lowercase English letters.
Solution
Method 1 - Iteration
To solve this problem:
- Iterate through the
wordsarray while keeping track of the index. - For each word, check if the character
xexists in the word (usingcontainsin Java or theinoperator in Python). - If
xexists in the word, append the index to the resulting array. - Return the resulting array.
Code
Java
public class Solution {
public List<Integer> findWordsContainingChar(String[] words, char x) {
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
if (words[i].indexOf(x) != -1) {
ans.add(i);
}
}
return ans;
}
Python
class Solution:
def findWordsContainingChar(self, words: List[str], x: str) -> List[int]:
ans: List[int] = []
for idx, word in enumerate(words):
if x in word:
ans.append(idx)
return ans
Complexity
- ⏰ Time complexity:
O(n*m)- Checking for
xin a word: Assumingmas the average length of words, the check takesO(m)time. - Iteration through the array: If the array has
nelements, the total iteration takesO(n). - Overall: The time complexity is
O(n * m).
- Checking for
- 🧺 Space complexity:
O(n)- Elements in the
ansarray are indices. Its space complexity is proportional to the size of the output (up toO(n)). - No additional space apart from the result array is used, so the space complexity is
O(n).
- Elements in the