#1684
Count the Number of Consistent Strings
EasyArrayHash TableStringBit ManipulationCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n * m) | O(n * m) |
| Space | O(1) | O(k) |
💡
Intuition
Time O(n * m)Space O(k)
We can use a set to store the allowed characters for O(1) lookups, making the check for consistency much faster.
⚙️
Algorithm
5 steps- 1Step 1: Convert the allowed string into a set of characters for fast lookup.
- 2Step 2: Initialize a counter to zero for consistent strings.
- 3Step 3: For each word in the words array, check if all characters are in the set of allowed characters.
- 4Step 4: Increment the counter for each consistent word.
- 5Step 5: Return the counter after processing all words.
solution.py7 lines
1def countConsistentStrings(allowed, words):
2 allowed_set = set(allowed)
3 count = 0
4 for word in words:
5 if all(char in allowed_set for char in word):
6 count += 1
7 return countℹ
Complexity note: The time complexity remains O(n * m) but with faster character checks due to the set. Space complexity is O(k) where k is the number of distinct characters in allowed.
- 1Using a set for allowed characters allows for O(1) lookups, significantly speeding up the consistency checks.
- 2Brute force is often a good starting point, but understanding how to optimize can lead to better performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.