Leetcode 1684: Count the Number of Consistent Strings

grid47
grid47
Exploring patterns and algorithms
May 22, 2024 5 min read

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. Return the number of consistent strings in the array words.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `allowed` and an array `words`.
Example: allowed = 'abc', words = ['a', 'ab', 'abc', 'abcd', 'bc']
Constraints:
• 1 <= words.length <= 10^4
• 1 <= allowed.length <= 26
• 1 <= words[i].length <= 10
• The characters in allowed are distinct.
• words[i] and allowed contain only lowercase English letters.
Output: Return the number of consistent strings in the array `words`.
Example: Output: 5
Constraints:
Goal: The goal is to count how many strings in the array `words` consist solely of characters from the `allowed` string.
Steps:
• Initialize a variable to store the count of consistent strings.
• Create a boolean array to track which characters are allowed.
• Iterate through each string in `words` and check if all its characters are present in the `allowed` string.
• For each word, if any character is not in the `allowed` string, it is not consistent, so skip counting it.
• Return the count of consistent strings.
Goal: The input string `allowed` and the array `words` must satisfy the following constraints:
Steps:
• 1 <= words.length <= 10^4
• 1 <= allowed.length <= 26
• 1 <= words[i].length <= 10
• The characters in allowed are distinct.
• words[i] and allowed contain only lowercase English letters.
Assumptions:
• The string `allowed` contains distinct lowercase English characters.
• All input strings and arrays will be valid as per the constraints.
Input: Input: allowed = 'abc', words = ['a', 'ab', 'abc', 'abcd', 'bc']
Explanation: All strings are consistent because they contain only characters from 'abc'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus