Count the Number of Consistent Strings - Problem

You are given a string allowed consisting of distinct characters and an array of strings words.

A string is consistent if all characters in the string appear in the string allowed.

Return the number of consistent strings in the array words.

Input & Output

Example 1 — Basic Case
$ Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
Output: 2
💡 Note: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.
Example 2 — All Valid
$ Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
Output: 7
💡 Note: All strings are consistent since they only use allowed characters a, b, c.
Example 3 — None Valid
$ Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
Output: 4
💡 Note: Strings "cc", "acd", "ac", and "d" are consistent. Others contain characters not in "cad".

Constraints

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

Visualization

Tap to expand
Count the Number of Consistent StringsAllowed Characters"ab"abCheck each word: Does it only use allowed characters?"ad""bd""aaab""baa""badab"has 'd' ✗has 'd' ✗only a,b ✓only a,b ✓has 'd' ✗Result: 2 consistent strings
Understanding the Visualization
1
Input
allowed="ab", words=["ad","bd","aaab","baa","badab"]
2
Check Each Word
Verify if all characters in each word exist in allowed
3
Count Valid
"aaab" and "baa" are consistent → count = 2
Key Takeaway
🎯 Key Insight: Pre-process allowed characters into a hash set or bitmask for fast O(1) character lookups
Asked in
Amazon 15 Microsoft 8
23.5K Views
Medium Frequency
~10 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