Find Words Containing Character - Complete Solution Guide
Find Words Containing Character is LeetCode problem 2942, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
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 . Note that the returned array may be in any order. Example 1: Input: words = ["leet","code"], x = "e" Output: [0,1] Explanation: "e" occurs in both words: "l ee t", and "cod e ". Hence, we return indices 0 and 1. Example 2: Input: words = ["abc","bcd","aaaa","cbc"], x = "a" Output: [0,2] Explanation: "a" occurs in " a bc", and " aaaa ". Hence, we re
Detailed Explanation
The problem asks you to find all words in a given array of strings that contain a specific character. The input is a list of strings (words) and a single character (x). The output is a list of indices, where each index corresponds to a word in the input array that contains the character x. The order of indices in the output doesn't matter. For example, if the input words are ['leet', 'code'] and x is 'e', the output should be [0, 1] because 'e' is present in both words at indices 0 and 1.
Solution Approach
The provided solutions all employ a straightforward iterative approach. They iterate through each word in the input array. For each word, they check if the target character 'x' is present. If it is, the index of that word is added to the result list. This approach directly addresses the problem's requirement of finding and returning the indices of words containing the character.
Step-by-Step Algorithm
- Step 1: Initialize an empty list (or array) called `result` to store the indices of words containing the character 'x'.
- Step 2: Iterate through the input array `words` using a loop. The loop variable will keep track of the index of each word.
- Step 3: Inside the loop, check if the character 'x' is present in the current word using an appropriate string function (e.g., `in` in Python, `indexOf` in Java, `find` in C++, manual character comparison in C).
- Step 4: If the character 'x' is found in the current word, add the index of the word (the loop variable) to the `result` list.
- Step 5: After iterating through all words, return the `result` list.
Key Insights
- Insight 1: The problem involves iterating through each word in the input array and checking if a specific character exists within that word.
- Insight 2: A simple linear scan of each word is sufficient to solve this problem. No complex data structures are needed.
- Insight 3: The `in` operator (Python), `indexOf` (Java), `find` (C++), or a manual character-by-character search (C) efficiently checks for character presence in each string.
Complexity Analysis
Time Complexity: O(n*m)
Space Complexity: O(n)
Topics
This problem involves: Array, String.
Companies
Asked at: Deliveroo.