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 <= 50
1 <= words[i].length <= 50
x
is a lowercase English letter.words[i]
consists only of lowercase English letters.
Solution
Method 1 - Iteration
To solve this problem:
- Iterate through the
words
array while keeping track of the index. - For each word, check if the character
x
exists in the word (usingcontains
in Java or thein
operator in Python). - If
x
exists in the word, append the index to the resulting array. - Return the resulting array.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n*m)
- Checking for
x
in a word: Assumingm
as the average length of words, the check takesO(m)
time. - Iteration through the array: If the array has
n
elements, the total iteration takesO(n)
. - Overall: The time complexity is
O(n * m)
.
- Checking for
- 🧺 Space complexity:
O(n)
- Elements in the
ans
array 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