Skip to content

Commit a270b70

Browse files
authored
Create 2942-find-words-containing-character.java
1 parent c4998bd commit a270b70

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// 🔹 Problem: 2942. Find Words Containing Character
2+
// 🔹 Link: https://leetcode.com/problems/find-words-containing-character/
3+
//
4+
// 🔹 Explanation:
5+
// We are given an array of words and a character `x`.
6+
// The task is to return the indices of all words that contain the character `x`.
7+
// For each word, we check every character.
8+
// If we find a match, we store that index in the result list and move to the next word.
9+
//
10+
// 🔹 Approach:
11+
// 1. Initialize an empty list to store indices.
12+
// 2. Iterate through each word in the array by index.
13+
// 3. Convert the word into a char array and check each character.
14+
// 4. If a character matches `x`, add the index to the result list and break (to avoid duplicates).
15+
// 5. Return the list of indices.
16+
//
17+
// 🔹 Complexity Analysis:
18+
// Time Complexity: O(N * L)
19+
// - N = number of words
20+
// - L = average length of each word
21+
// - Worst case: we may check all characters of all words.
22+
//
23+
// Space Complexity: O(1)
24+
// - We only use a result list (output itself is not counted as extra space).
25+
//
26+
// 🔹 Example:
27+
// Input: words = ["leet","code"], x = 'e'
28+
// Output: [0,1]
29+
// Explanation: 'e' is found in both "leet" and "code".
30+
31+
class Solution {
32+
public List<Integer> findWordsContaining(String[] words, char x) {
33+
List<Integer> list = new ArrayList<>();
34+
for (int i = 0; i < words.length; i++) {
35+
for (char ch : words[i].toCharArray()) {
36+
if (ch == x) {
37+
list.add(i);
38+
break;
39+
}
40+
}
41+
}
42+
return list;
43+
}
44+
}

0 commit comments

Comments
 (0)