Count the Number of Consistent Strings - 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.

Return the number of consistent strings in the array words.

Input & Output

Example 1 — 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'.
Example 2 — All Valid
$ Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
Output: 7
💡 Note: All strings are consistent since they only use allowed characters a, b, c.
Example 3 — None Valid
$ 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 characters not in "cad".

Constraints

  • 1 ≤ words.length ≤ 104
  • 1 ≤ allowed.length ≤ 26
  • 1 ≤ words[i].length ≤ 10
  • The characters in allowed are distinct
  • words[i] and allowed contain only lowercase English letters

Visualization

Tap to expand
Count the Number of Consistent Strings INPUT allowed = "ab" a b HashSet of allowed words array: "ad" "bd" "aaab" "baa" "badab" Character Check: "ad": d not in set "bd": d not in set "aaab": all OK "baa": all OK "badab": d not in set ALGORITHM STEPS 1 Build HashSet Add each char from "allowed" to set 2 Initialize counter count = 0 3 Check each word For each word, check if all chars are in set 4 Count if consistent If all chars valid, increment count for word in words: for char in word: if char not in set: break FINAL RESULT Consistent Words Found: "aaab" OK - all chars in {a,b} "baa" OK - all chars in {a,b} Inconsistent (excluded): "ad", "bd", "badab" (contain 'd' not in set) OUTPUT 2 2 consistent strings in the array Key Insight: Using a HashSet for the allowed characters enables O(1) lookup time for each character check. This optimizes the overall time complexity to O(n*m) where n = number of words and m = average word length. Space complexity is O(k) where k = length of allowed string (at most 26 for lowercase letters). TutorialsPoint - Count the Number of Consistent Strings | Hash Set Optimization
Asked in
Amazon 15 Microsoft 8
23.5K Views
Medium Frequency
~10 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen