Find Words Containing Character (LeetCode 2942): Solution and Explanation

Easy
Array
String

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

  1. Create an empty list result.
  2. For each index i, check whether x occurs in words[i].
  3. If it does, append i to result.
  4. Return result.

Step-by-step example

words = ["leet","code"], x = "e"
  1. 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.
  2. Word 1 is "code". 'c', 'o' and 'd' are not 'e', the fourth letter is 'e', so 1 goes into result.
  3. 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 result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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.