Problem Statement:
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.
The returned array can be in any order.
Example:
Input: words = [“leet”, “code”], x = “e”
Output: [0, 1]
Input: words = [“abc”, “bcd”, “aaaa”, “cbc”], x = “a”
Output: [0, 2]
Input: words = [“abc”, “bcd”, “aaaa”, “cbc”], x = “z”
Output: []
Constraints:
- 1 ≤ words.length ≤ 50
- 1 ≤ words[i].length ≤ 50
- x is a lowercase English letter
- words[i] consists only of lowercase English letters
Approach:
- Use two nested loops: Outer loop for each word, inner loop for each character in the word.
- If character
xis found in a word, push its index to the result array and break.
Time and Space Complexity:
- Time Complexity: O(m × n) — where
mis the number of words, andnis the max length of a word. - Space Complexity: O(1) — constant extra space (excluding result array).
var findWordsContaining = function(words, x) {
let res = [];
for (let i = 0; i < words.length; i++) {
for (let j = 0; j < words[i].length; j++) {
if (words[i][j] === x) {
res.push(i);
break;
}
}
}
return res;
};
int* findWordsContaining(char** words, int wordsSize, char x, int* returnSize) {
int* result = (int*)malloc(sizeof(int) * wordsSize);
*returnSize = 0;
for (int i = 0; i < wordsSize; i++) {
for (int j = 0; words[i][j] != '\0'; j++) {
if (words[i][j] == x) {
result[(*returnSize)++] = i;
break;
}
}
}
return result;
}
class Solution {
public:
vector<int> findWordsContaining(vector<string>& words, char x) {
vector<int> result;
for (int i = 0; i < words.size(); i++) {
for (char c : words[i]) {
if (c == x) {
result.push_back(i);
break;
}
}
}
return result;
}
};
class Solution {
public List<Integer> findWordsContaining(String[] words, char x) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
for (char c : words[i].toCharArray()) {
if (c == x) {
result.add(i);
break;
}
}
}
return result;
}
}
class Solution(object):
def findWordsContaining(self, words, x):
result = []
for i, word in enumerate(words):
for ch in word:
if ch == x:
result.append(i)
break
return result
public class Solution {
public IList<int> FindWordsContaining(string[] words, char x) {
var result = new List<int>();
for (int i = 0; i < words.Length; i++) {
foreach (char c in words[i]) {
if (c == x) {
result.Add(i);
break;
}
}
}
return result;
}
}
