Count the Number of Consistent Strings (LeetCode 1684): Solution and Explanation

Easy
Array
Hash Table
String
Bit Manipulation
Counting

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

  1. Start with mask = 0 and, for each letter c of allowed, set mask |= 1 << (c - 'a').
  2. Set count = 0.
  3. For each word, test every letter with mask & (1 << (c - 'a')). If a test is 0, mark the word bad and stop.
  4. If no letter failed, add one to count.
  5. Return count.

Step-by-step example

allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
  1. 'a' sets bit 0 and 'b' sets bit 1, so mask = 11 in binary (3).
  2. "ad": 'a' passes, 'd' tests bit 3, which is 0. Rejected.
  3. "bd": 'b' passes, 'd' fails. Rejected.
  4. "aaab": all four letters pass. count = 1.
  5. "baa": all letters pass. count = 2.
  6. "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 count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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).

Space

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.