#2942
Find Words Containing Character
EasyArrayStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can achieve better efficiency by directly iterating through the words and checking for the character in a single pass, reducing unnecessary checks.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty list to store indices.
- 2Step 2: Loop through each word in the words array using its index.
- 3Step 3: Use the 'in' operator (or equivalent) to check if x is in the current word.
- 4Step 4: If true, append the index to the list.
- 5Step 5: Return the list of indices.
solution.py2 lines
1def find_words_containing_char(words, x):
2 return [i for i, word in enumerate(words) if x in word]ℹ
Complexity note: The time complexity is O(n) because we only loop through the words once. The space complexity is O(n) for storing the indices of the words that contain the character.
- 1Using built-in string functions can simplify code and improve readability.
- 2Understanding the difference between time complexity helps in optimizing solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.