Difficulty: Easy | Acceptance: 90.40% | Paid: No Topics: Array, String
Given a 0-indexed array of strings words and a character x, return an array of indices i (in increasing order) such that words[i] contains the character x.
- Examples
- Constraints
- Built-in Functions
- Manual Character Check
Examples
Example 1
Input:
words = ["leet","code"], x = "e"
Output:
[0,1]
Explanation: “e” occurs in both words: “leet”, and “code”. Hence, we return indices 0 and 1.
Example 2
Input:
words = ["abc","bcd","aaaa","cbc"], x = "a"
Output:
[0,2]
Explanation: “a” occurs in “abc”, and “aaaa”. Hence, we return indices 0 and 2.
Example 3
Input:
words = ["abc","bcd","aaaa","cbc"], x = "z"
Output:
[]
Explanation: “z” does not occur in any of the words. Hence, we return an empty array.
Constraints
1 <= words.length <= 50
1 <= words[i].length <= 300
words[i] consists of lowercase English letters.
x is a lowercase English letter.
Built-in Functions
Intuition Use language-specific built-in methods to check if a character exists in a string, which is the most straightforward and readable approach.
Steps
- Iterate through each word with its index
- Use built-in contains/indexOf/includes method to check if character exists
- If found, add the index to result array
- Return the result array
class Solution:
def findWordsContaining(self, words: List[str], x: str) -> List[int]:
result = []
for i, word in enumerate(words):
if x in word:
result.append(i)
return resultComplexity
- Time: O(n × m) where n is the number of words and m is the average word length
- Space: O(k) where k is the number of words containing the character
- Notes: Most readable and idiomatic approach for each language
Manual Character Check
Intuition Manually iterate through each character of every word to check for the target character, demonstrating the underlying algorithm without relying on built-in string methods.
Steps
- Iterate through each word with its index
- For each word, iterate through all its characters
- If character matches x, add index to result and break (move to next word)
- Return the result array
class Solution:
def findWordsContaining(self, words: List[str], x: str) -> List[int]:
result = []
for i, word in enumerate(words):
for c in word:
if c == x:
result.append(i)
break
return resultComplexity
- Time: O(n × m) where n is the number of words and m is the average word length
- Space: O(k) where k is the number of words containing the character
- Notes: Same complexity as built-in approach, but demonstrates fundamental iteration logic