Count the Number of Consistent Strings(#1684)
Category: String, Hash Set, Foundation
๐งฉ 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
- 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
โข We first convert the 'allowed' string into a Set for O(1) lookups.
โข Then, for each word in the 'words' array, we check whether every character in that word exists in the Set using the .every() method.
โข If all characters are allowed, we increment the count.
๐ป Code
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'.