LeetCode 2942: Find Words Containing Character Solution
Master LeetCode problem 2942 (Find Words Containing Character), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To solve this problem, we iterate through each word in the given array and check if the character x is present in that word. If the character is found, we add the index of that word to the result array.
Finally, we return the result array containing the indices of words that contain the character x.
- Initialize an empty array
resultto store the indices of words containing characterx. - Iterate through each word in the input array
words. - For each word, check if the character
xis present in that word. - If
xis found in the word, add the index of that word to theresultarray. - Return the
resultarray containing the indices of words that contain the characterx.
Time Complexity: O(n*m) where n is the number of words and m is the average length of words in the input array.
Space Complexity: O(n) where n is the number of words in the input array.
: :
Solution Code
import java.util.ArrayList;
import java.util.List;
class Solution {
public int[] findWordsContainingChar(String[] words, char x) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
if (words[i].contains(String.valueOf(x))) {
result.add(i);
}
}
return result.stream().mapToInt(Integer::intValue).toArray();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2942 (Find Words Containing Character)?
This page provides optimized solutions for LeetCode problem 2942 (Find Words Containing Character) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2942 (Find Words Containing Character)?
The time complexity for LeetCode 2942 (Find Words Containing Character) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2942 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2942 in Java, C++, or Python.