Count the Number of Consistent Strings
(#1684), Easy
Category: Array, Hash Table, String, Bit Manipulation, Counting
Problem Statement
You are given a string 'allowed' consisting of distinct characters and an array of strings 'words'. A string is considered consistent if all characters in the string appear in the allowed string. Return the number of consistent strings in the words array.
Examples
Input: allowed = "ab", words = ["a", "b", "ab", "abc"]
Output: 3
Explanation:
- Allowed characters are: 'a', 'b'
- Word 1: 'a' → all characters allowed → ✅
- Word 2: 'b' → all characters allowed → ✅
- Word 3: 'ab' → all characters allowed → ✅
- Word 4: 'abc' → contains 'c' which is not allowed → ❌
- Total consistent strings = 3
Approach
Using Hash Set for Allowed Characters
- Convert the `allowed` string into a Set to enable O(1) lookups for each character.
- Initialize a counter variable `count` to keep track of consistent strings.
- Loop through each word in the `words` array:
- - For each word, check if every character exists in the Set using `.every()`.
- - If the word is fully consistent, increment the `count`.
- Return the final value of `count`.
var countConsistentStrings = function(allowed, words) {
const allowedSet = new Set(allowed);
let count = 0;
for (const word of words) {
let isConsistent = [...word].every(char => allowedSet.has(char));
if (isConsistent) {
count++;
}
}
return count;
};
Complexity
Time: O(n * m), where n is the number of words and m is the average length of a word.
Space: O(k), where k is the number of unique characters in 'allowed'.