Find Words Containing Character - Problem

You're working as a content moderator and need to quickly identify words that contain a specific character. Given a 0-indexed array of strings words and a target character x, your task is to return an array of indices representing all words that contain the character x.

Goal: Find all word positions that contain the target character

Input: An array of strings and a single character

Output: Array of indices (positions) where the character appears

Note: The returned array can be in any order, making this problem flexible for optimization!

Example: If words = ["hello", "world", "leetcode"] and x = "l", return [0, 1, 2] because all three words contain the letter 'l'.

Input & Output

example_1.py โ€” Basic Case
$ Input: words = ["leet", "code"], x = "e"
โ€บ Output: [0]
๐Ÿ’ก Note: Only the word "leet" at index 0 contains the character 'e'. The word "code" does not contain 'e'.
example_2.py โ€” Multiple Matches
$ Input: words = ["hello", "world", "leetcode"], x = "o"
โ€บ Output: [1, 2]
๐Ÿ’ก Note: Words "world" (index 1) and "leetcode" (index 2) contain the character 'o'. "hello" does not contain 'o'.
example_3.py โ€” All Match
$ Input: words = ["abc", "bcd", "aaaa", "cbc"], x = "a"
โ€บ Output: [0, 2]
๐Ÿ’ก Note: Words at indices 0 ("abc") and 2 ("aaaa") contain the character 'a'. Words "bcd" and "cbc" do not contain 'a'.

Constraints

  • 1 โ‰ค words.length โ‰ค 50
  • 1 โ‰ค words[i].length โ‰ค 50
  • x is a single character
  • words[i] and x consist of only lowercase English letters

Visualization

Tap to expand
Filing Cabinet Search for Character 'l'Folder 0"hello"Contains 'l' โœ“0Folder 1"world"Contains 'l' โœ“1Folder 2"leetcode"Contains 'l' โœ“2Search Results[0, 1, 2]Algorithm Steps:1. Iterate through each word in the array2. Check if current word contains target character 'l'3. If found, add current index to result array4. Return array of all matching indices
Understanding the Visualization
1
Start with first folder
Check if 'hello' contains 'l' โ†’ Yes, mark index 0
2
Check next folder
Check if 'world' contains 'l' โ†’ Yes, mark index 1
3
Continue systematically
Check if 'leetcode' contains 'l' โ†’ Yes, mark index 2
4
Collect results
Return all marked indices: [0, 1, 2]
Key Takeaway
๐ŸŽฏ Key Insight: This problem is straightforward - iterate once through the array and use built-in string search methods. No complex algorithms needed!
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
28.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen