Find Words Containing Character - Problem

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: The returned array may be in any order.

Input & Output

Example 1 — Basic Case
$ Input: words = ["leet","code","leetcode"], x = "e"
Output: [0,1,2]
💡 Note: All words contain 'e': "leet" has 'e' at positions 1,2, "code" has 'e' at position 3, "leetcode" has 'e' at positions 1,2,5,6
Example 2 — Some Words Match
$ Input: words = ["abc","bcd","aaaa","cbc"], x = "a"
Output: [0,2]
💡 Note: Only "abc" (index 0) and "aaaa" (index 2) contain the character 'a'
Example 3 — No Matches
$ Input: words = ["abc","bcd","def"], x = "z"
Output: []
💡 Note: None of the words contain the character 'z', so return empty array

Constraints

  • 1 ≤ words.length ≤ 50
  • 1 ≤ words[i].length ≤ 50
  • x is a lowercase English letter
  • words[i] consists only of lowercase English letters

Visualization

Tap to expand
Find Words Containing Character INPUT words array: [0] "leet" [1] "code" [2] "leetcode" Character to find: x = "e" Find 'e' in each word l e e t cod e l ee tcod e ALGORITHM STEPS 1 Initialize Result Create empty array [] 2 Loop Through Words For each word at index i 3 Check Contains word.contains(x)? 4 Add Index If yes, add i to result Iteration Details: i=0: "leet".contains("e") OK i=1: "code".contains("e") OK i=2: "leetcode".contains("e") OK All words contain 'e'! FINAL RESULT Indices of matching words: 0 1 2 "leet" "code" "leetcode" Output: [0, 1, 2] Verification: All 3 words contain 'e' All indices returned Key Insight: The built-in string contains() method makes this problem straightforward. Simply iterate through each word, check if it contains the target character, and collect the indices where true. Time Complexity: O(n * m) where n = number of words, m = average word length. TutorialsPoint - Find Words Containing Character | Built-in String Contains Approach
Asked in
Google 25 Amazon 20 Microsoft 15
21.1K Views
Medium Frequency
~10 min Avg. Time
845 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