Count the Number of Consistent Strings — LeetCode 1684 Python Solution

EasyBit ManipulationArrayHash TableStringCounting
Problem
#1684
Reading time
2 min

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

Example

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

Python solution

Python
class Solution:
    def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
        s = set(allowed)
        return sum(all(c in s for c in w) for w in words)

Complexity

MeasureComplexity
TimeO(m)
SpaceO(C) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1684. Count the Number of Consistent Strings is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1684. Count the Number of Consistent Strings?
LeetCode 1684. Count the Number of Consistent Strings is rated Easy on LeetCode.
What is the time complexity of LeetCode 1684. Count the Number of Consistent Strings?
The Python solution on this page runs in O(m).
What is the space complexity of LeetCode 1684. Count the Number of Consistent Strings?
The Python solution on this page uses O(C) auxiliary space.
What topics does LeetCode 1684. Count the Number of Consistent Strings cover?
LeetCode 1684. Count the Number of Consistent Strings is tagged Bit Manipulation, Array, Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview