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.
Example 1:
Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"] Output: 2 Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.
Example 2:
Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"] Output: 7 Explanation: All strings are consistent.
Example 3:
Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"] Output: 4 Explanation: Strings "cc", "acd", "ac", and "d" are consistent.
Constraints:
1 <= words.length <= 1041 <= allowed.length <= 261 <= words[i].length <= 10- The characters in
allowedare distinct. words[i]andallowedcontain only lowercase English letters.
Approach 01:
-
C++
-
Python
class Solution {
public:
int countConsistentStrings(string allowed, vector<string>& words) {
int result = 0;
for (auto &word : words) {
int flag = 1;
for (auto &ch : word) {
if (allowed.find(ch) == -1) {
flag = 0;
break;
}
}
if (flag) {
result += 1;
}
}
return result;
}
};
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
result = 0
for word in words:
flag = 1
for ch in word:
if ch not in allowed:
flag = 0
break
if flag:
result += 1
return result
Time Complexity
- Checking Each Word:
The algorithm iterates over each word in the
wordsvector. Letnbe the number of words andmbe the maximum length of a word. For each word, it iterates over its characters to check if they exist in theallowedstring. This results in a time complexity of \(O(n \cdot m)\) in the worst case. - Finding Characters in the Allowed String:
The
findfunction used to check if a character is present in theallowedstring has a time complexity of \(O(|allowed|)\), where|allowed|is the length of the allowed string. Since this check is performed for every character in each word, it contributes to the overall complexity of \(O(n \cdot m \cdot |allowed|)\). - Overall Time Complexity:
The overall time complexity is \(O(n \cdot m \cdot |allowed|)\), where
nis the number of words,mis the maximum length of a word, and|allowed|is the length of the allowed string. If|allowed|is treated as a constant (e.g., 26 lowercase English letters), the complexity can be simplified to \(O(n \cdot m)\).
Space Complexity
- Space for Variables:
The solution uses a few local variables:
resultto count the number of consistent strings andflagto check if all characters in a word are allowed. This requires \(O(1)\) space. - Space for Input Storage:
The space required for the input
wordsandallowedstrings is already given as part of the input and does not count towards the space complexity of the algorithm itself. - Overall Space Complexity:
The overall space complexity is \(O(1)\) because no additional data structures or dynamic memory allocations are used.