Count Strings With Required Characters - Problem

You are given a string required containing distinct lowercase English letters and an array of strings words.

A word is considered matching if it contains at least one character that also appears in required.

Return the count of matching words in the array words.

Input & Output

Example 1 — Some Match
$ Input: required = "ae", words = ["apple","box","cat","dog","egg"]
Output: 3
💡 Note: "apple" contains 'a' and 'e', "cat" contains 'a', "egg" contains 'e'. "box" and "dog" contain neither 'a' nor 'e'.
Example 2 — All Match
$ Input: required = "xyz", words = ["fox","yell","buzz","ax","lazy"]
Output: 5
💡 Note: Every word contains at least one of 'x', 'y', or 'z': fox(x), yell(y), buzz(z), ax(x), lazy(y,z).
Example 3 — None Match
$ Input: required = "q", words = ["hello","world","abc","def"]
Output: 0
💡 Note: No word contains the character 'q'.

Constraints

  • 1 ≤ words.length ≤ 10⁴
  • 1 ≤ required.length ≤ 26
  • 1 ≤ words[i].length ≤ 10
  • The characters in required are distinct
  • words[i] and required contain only lowercase English letters

Visualization

Tap to expand
Count the Number of Strings With Required Characters INPUT required = "ae" words: "apple" "box" "cat" "dog" "egg" Valid = has at least one char from required HASH SET CHECK 1 Build Set {'a','e'} 2 Check each password "apple" 'a' ∈ Set → ✅ "box" b,o,x ∉ Set → ❌ "cat" 'a' ∈ Set → ✅ "dog" d,o,g ∉ Set → ❌ "egg" 'e' ∈ Set → ✅ O(1) lookup per char RESULT Output: 3 valid words ✅ apple, cat, egg ❌ box, dog Key Insight: Convert the required string to a Set for O(1) character lookup. For each password, check if ANY character is in the set — break early on first match. Time: O(n×m), Space: O(r≤26). TutorialsPoint - Count the Number of Strings With Required Characters
Asked in
Amazon 15 Google 10 Microsoft 8
19.0K Views
Medium Frequency
~8 min Avg. Time
320 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