Count the Number of Consistent Strings - Problem
You are a content moderator for a social media platform, and you need to validate user posts based on allowed characters. You have been given a string of allowed characters and an array of user-generated strings that need to be checked.
A string is considered consistent if all characters in the string appear in the allowed characters string. Your task is to count how many strings in the array are consistent.
Goal: Return the number of consistent strings in the array.
Example: If allowed characters are "abc" and we have words ["a", "b", "c", "ab", "ac", "bc", "abc", "xyz"], then 7 strings are consistent (all except "xyz" which contains characters not in the allowed set).
Input & Output
example_1.py โ Basic case
$
Input:
allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
โบ
Output:
2
๐ก Note:
Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'. The other strings contain 'd' which is not allowed.
example_2.py โ All consistent
$
Input:
allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
โบ
Output:
7
๐ก Note:
All strings are consistent as they only use characters from the allowed set {a, b, c}.
example_3.py โ None consistent
$
Input:
allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
โบ
Output:
4
๐ก Note:
Strings "cc", "acd", "ac", and "d" are consistent. Others contain 'b' which is not in allowed characters.
Constraints
- 1 โค words.length โค 104
- 1 โค allowed.length โค 26
- 1 โค words[i].length โค 10
- The characters in allowed are distinct
- allowed and words[i] consist of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Create Approval List
Convert allowed characters string into a fast lookup table (hash set)
2
Check Each Post
For each user post (word), examine every character
3
Validate Characters
Use hash set to instantly check if each character is approved
4
Count Approved Posts
Increment counter only if all characters in the post are approved
Key Takeaway
๐ฏ Key Insight: Converting the allowed characters to a hash set transforms expensive O(k) character searches into O(1) lookups, dramatically improving performance for large inputs while maintaining simple, readable code.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code