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:
| |
Example 2:
| |
Example 3:
| |
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
| |
| |
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