Count the Number of Consistent Strings(#1684)

Category: String, Hash Set, Foundation

๐Ÿงฉ Problem Statement

You are given a string 'allowed' consisting of distinct characters and an array of strings 'words'. A string is considered consistent if all characters in the string appear in the allowed string. Return the number of consistent strings in the words array.

๐Ÿ“š Examples

Input: allowed = "ab", words = ["a", "b", "ab", "abc"]

Output: 3

Explanation:
  • Allowed characters are: 'a', 'b'
  • Word 1: 'a' โ†’ all characters allowed โ†’ โœ…
  • Word 2: 'b' โ†’ all characters allowed โ†’ โœ…
  • Word 3: 'ab' โ†’ all characters allowed โ†’ โœ…
  • Word 4: 'abc' โ†’ contains 'c' which is not allowed โ†’ โŒ
  • Total consistent strings = 3

๐Ÿง  Approach

โ€ข We first convert the 'allowed' string into a Set for O(1) lookups.

โ€ข Then, for each word in the 'words' array, we check whether every character in that word exists in the Set using the .every() method.

โ€ข If all characters are allowed, we increment the count.

๐Ÿ’ป Code

var countConsistentStrings = function(allowed, words) {
  const allowedSet = new Set(allowed);
  let count = 0;

  for (const word of words) {
    let isConsistent = [...word].every(char => allowedSet.has(char));
    if (isConsistent) {
      count++;
    }
  }

  return count;
};

๐Ÿ“ˆ Complexity

Time: O(n * m), where n is the number of words and m is the average length of a word.

Space: O(k), where k is the number of unique characters in 'allowed'.

๐ŸŽฌ Watch Explanation

๐Ÿ“Ž Resources