Given a string allowed consisting of distinct characters and an array of strings words, return the number of consistent strings in the array. A string is consistent if all characters in the string appear in the string allowed.
allowed contain non-alphabetic characters?
allowed contains distinct alphabetic characters.words case-sensitive?
allowed or the array words?
allowed <= 100, number of words <= 1000, total characters in words <= 10000).allowed string into a set of characters for O(1) average-time complexity membership checks.words list and check if all characters in the word are present in the allowed_set.def countConsistentStrings(allowed, words):
allowed_set = set(allowed)
count = 0
for word in words:
if all(char in allowed_set for char in word):
count += 1
return count
Convert allowed to Set: We convert the string allowed into a set allowed_set to leverage the average O(1) lookup time for determining if a character is in allowed.
words array, we use a generator expression within all() to check if every character in the word is present in allowed_set.count by 1.allowed to a set: O(L), where L is the length of allowed.In summary, the total time complexity is O(L + W * N). Here, L is typically much smaller than W * N, so the dominating term is W * N.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?