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
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Video explanation
Here is the video explaining this method in detail. Please check it out:
Method 1 - Using Set
The task is to count how many strings in the array words
are composed solely of characters found in the string allowed
.
Here are the steps:
- Allowed Set: Convert the
allowed
string to a set for O(1) lookup times. - Consistency Check: For each word, check if all characters are in the allowed set.
- Count Consistent Strings: Increment the count for each consistent word.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + m.k)
, wheren
is the length of theallowed
string andm
is number of words andk
is the length of the word.- Conversion to Set: Converting the
allowed
string to a set takes O(n), wheren
is the length of theallowed
string. - Checking Consistency: For each word in the
words
list, we check if all characters are in theallowed_set
.- This involves iterating through each character in the word.
- The worst-case time complexity to check each word is O(k) where
k
is the length of the word. - Since there are
m
words and each word has at mostk
characters, the total time complexity for checking consistency is O(m * k).
- Conversion to Set: Converting the
- 🧺 Space complexity:
O(n)
for storing allowed in set
Method 2 - Using Bitmask
Here is the approach:
- Each Character as a Bit:
- There are 26 lowercase English letters, so we can use an integer with a 26-bit representation.
- Each bit in the integer will represent whether a particular character is allowed or part of a word.
- Allowed Bitmask:
- Convert the
allowed
string into a bitmask where each bit is set if the corresponding character exists in theallowed
string.
- Convert the
- Word Bitmask:
- For each word in the
words
array, create a bitmask to represent characters in the word.
- For each word in the
- Consistency Check:
- A word is consistent if its bitmask is a subset of the allowed bitmask. This can be checked using bitwise operations.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + m.k)
. Creating the bitmask for theallowed
string involves iterating through its characters, takingO(n)
time. Then we process each word. Generating the bitmask for the word involves iterating through its characters, takingO(k)
time given its length isk
and the comparing the word with allowed bitmask takesO(1)
time. - 🧺 Space complexity:
O(1)
. Only a few integers are used for bitmasks and counters.