Count the Number of Consistent Strings (LeetCode 1684): Solution and Explanation
Count the words whose letters all come from the string allowed.
Intuition
The whole problem is a membership test repeated many times: is this letter in allowed? Searching the allowed string for every letter works but repeats the same search over and over.
There are only 26 letters, so the set of allowed letters fits in the low 26 bits of one integer. Bit k is 1 when the k-th letter of the alphabet is allowed.
With that mask, checking a letter is a single AND with 1 << (c - 'a'). A word is consistent when no letter comes back 0, and you can stop checking a word at its first failing letter.
Approach: 26-bit letter mask
- Start with
mask = 0and, for each lettercofallowed, setmask |= 1 << (c - 'a'). - Set
count = 0. - For each word, test every letter with
mask & (1 << (c - 'a')). If a test is 0, mark the word bad and stop. - If no letter failed, add one to
count. - Return
count.
Step-by-step example
allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
- 'a' sets bit 0 and 'b' sets bit 1, so mask = 11 in binary (3).
- "ad": 'a' passes, 'd' tests bit 3, which is 0. Rejected.
- "bd": 'b' passes, 'd' fails. Rejected.
- "aaab": all four letters pass. count = 1.
- "baa": all letters pass. count = 2.
- "badab": 'b' and 'a' pass, 'd' fails. Rejected. Return 2.
Code: Python, Java, C++
1class Solution:
2 def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
3 mask = 0
4 for c in allowed:
5 mask |= 1 << (ord(c) - ord('a'))
6 count = 0
7 for word in words:
8 ok = True
9 for c in word:
10 if not mask & (1 << (ord(c) - ord('a'))):
11 ok = False
12 break
13 if ok:
14 count += 1
15 return count1class Solution {
2 public int countConsistentStrings(String allowed, String[] words) {
3 int mask = 0;
4 for (char c : allowed.toCharArray()) {
5 mask |= 1 << (c - 'a');
6 }
7 int count = 0;
8 for (String word : words) {
9 boolean ok = true;
10 for (char c : word.toCharArray()) {
11 if ((mask & (1 << (c - 'a'))) == 0) {
12 ok = false;
13 break;
14 }
15 }
16 if (ok) {
17 count++;
18 }
19 }
20 return count;
21 }
22}1class Solution {
2public:
3 int countConsistentStrings(string allowed, vector<string>& words) {
4 int mask = 0;
5 for (char c : allowed) {
6 mask |= 1 << (c - 'a');
7 }
8 int count = 0;
9 for (const string& word : words) {
10 bool ok = true;
11 for (char c : word) {
12 if ((mask & (1 << (c - 'a'))) == 0) {
13 ok = false;
14 break;
15 }
16 }
17 if (ok) {
18 count++;
19 }
20 }
21 return count;
22 }
23};Time and space complexity
O(m + L)
Building the mask reads allowed once (m letters), and the scan does one AND per letter of the words (L letters in total).
O(1)
The mask is a single integer regardless of input size.
Other approaches
Hash set or boolean array (time O(m + L), space O(1))
Put the letters of allowed in a set (or a 26-entry boolean array) and look each word letter up. Same complexity, slightly more memory.
Word mask subset test (time O(m + L), space O(1))
Build a mask for each word too, then the word is consistent exactly when (wordMask | mask) == mask. Reads every letter of every word, with no early exit.
Common mistakes
- Searching the allowed string with indexOf or in for every letter. It is correct but repeats a linear search for each character.
- Counting a word before every letter has been checked. Count only after the inner loop finishes without a failure.
- Writing mask & 1 << c - 'a' without parentheses in C-like languages, where the shift and subtraction bind differently than you might expect.
Frequently asked questions
Why does a 32-bit int suffice for the mask?
There are 26 lowercase letters, so the highest bit ever set is bit 25, well inside a 32-bit integer.
Do repeated letters in a word matter?
No. A repeated letter just tests the same bit again. Only whether each letter is allowed matters, not how often it appears.
Is the bitmask faster than a set in practice?
Usually a little, since a bit test avoids hashing. The asymptotic cost is the same, so the main gain is simpler, allocation-free code.