Find Words Containing Character (LeetCode 2942): Solution and Explanation
Given a list of words and one letter x, return the indices of the words that contain x at least once. Any order is accepted.
Intuition
Every word is judged on its own. Whether "code" contains 'e' has nothing to do with whether "leet" does, so there is no shared state to build.
For one word, read its letters from left to right. The moment you see x, you know the answer for that word and can stop reading it. Only a word without x has to be read to the end.
Do that for every word and collect the indices that passed. Built-in checks like x in word, includes or indexOf do exactly this scan for you.
Approach: Linear scan with early stop
- Create an empty list
result. - For each index
i, check whetherxoccurs inwords[i]. - If it does, append
itoresult. - Return
result.
Step-by-step example
words = ["leet","code"], x = "e"
- Word 0 is "leet". Its first letter 'l' is not 'e', its second letter is 'e', so the scan stops and 0 goes into result.
- Word 1 is "code". 'c', 'o' and 'd' are not 'e', the fourth letter is 'e', so 1 goes into result.
- All words are done. Return [0,1].
Code: Python, Java, C++
1class Solution:
2 def findWordsContaining(self, words: List[str], x: str) -> List[int]:
3 result = []
4 for i, word in enumerate(words):
5 if x in word:
6 result.append(i)
7 return result1class Solution {
2 public List<Integer> findWordsContaining(String[] words, char x) {
3 List<Integer> result = new ArrayList<>();
4 for (int i = 0; i < words.length; i++) {
5 if (words[i].indexOf(x) != -1) {
6 result.add(i);
7 }
8 }
9 return result;
10 }
11}1class Solution {
2public:
3 vector<int> findWordsContaining(vector<string>& words, char x) {
4 vector<int> result;
5 for (int i = 0; i < (int)words.size(); i++) {
6 if (words[i].find(x) != string::npos) {
7 result.push_back(i);
8 }
9 }
10 return result;
11 }
12};Time and space complexity
O(L)
L is the total number of letters across all words. Each letter is read at most once, and the scan of a word stops at its first x.
O(1)
Nothing is stored besides the output list.
Other approaches
Letter sets (time O(L), space O(L))
Turn each word into a set of letters and test membership. It gives the same answer, but building the sets costs extra time and memory for a single query.
List comprehension or filter (time O(L), space O(1))
Write the same scan as one expression, for example [i for i, w in enumerate(words) if x in w]. Identical work, shorter code.
Common mistakes
- Adding the same index more than once when a word contains x several times. Stop at the first match or test containment once per word.
- Returning the words instead of their indices.
- In Go or C++, comparing a byte or char with a one-character string instead of a character.
Frequently asked questions
Does the order of the returned indices matter?
No. Any order is accepted, although a left-to-right scan naturally returns them in increasing order.
Why is this O(L) and not O(n * m)?
Both describe the same bound. With n words of length at most m, the total letter count L is at most n * m, and each letter is checked at most once.
What if no word contains x?
Return an empty list. Every word is scanned to the end and none passes the check.