Find Words Containing Character
Problem
You are given a list of strings words and a character x. Return a list of the indices of the words that contain the character x. The answer may be returned in any order.
words = ["leet","code"], x = "e"[0,1]def find_words_containing(words, x):
result = []
for i, w in enumerate(words):
if x in w:
result.append(i)
return result
function findWordsContaining(words, x) {
const result = [];
for (let i = 0; i < words.length; i++) {
if (words[i].includes(x)) {
result.push(i);
}
}
return result;
}
class Solution {
public List<Integer> findWordsContaining(String[] words, char x) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
if (words[i].indexOf(x) != -1) {
result.add(i);
}
}
return result;
}
}
vector<int> findWordsContaining(vector<string>& words, char x) {
vector<int> result;
for (int i = 0; i < (int)words.size(); i++) {
if (words[i].find(x) != string::npos) {
result.push_back(i);
}
}
return result;
}
Explanation
The task is a simple filter: keep the position of each word that contains the character x. Because we have to report indices, not the words themselves, we walk the list with an index counter rather than just iterating the values.
We maintain a result list. For each index i, we ask whether words[i] contains x using the built-in substring/contains check (in, includes, indexOf, or find).
If the character is present anywhere in that word, we append i to result. If not, we move on. The order we collect indices in is naturally ascending, which satisfies the "any order" requirement.
This is a single linear sweep over all the words, and the contains-check itself scans each word at most once, so the total work is proportional to the combined length of all the strings.
Example: words = ["leet","code"], x = 'e'. "leet" has an 'e' so we add index 0; "code" also has an 'e' so we add index 1. The answer is [0, 1].