POTD Leet Code – 1684. Count the Number of Consistent Strings in JavaScript

To solve the problem 1684. Count the Number of Consistent Strings in JavaScript, we need to count how many strings from a given array consist only of characters from a given allowed set of characters.

Problem Statement:

You’re given a string allowed that consists of distinct characters, and an array words where each string in words consists of only lowercase English letters. A string is consistent if all characters in the string appear in the string allowed.

The task is to return the number of consistent strings in the array words.

Example:

Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc","abcd"]
Output: 7
Explanation: The consistent strings are "a", "b", "c", "ab", "ac", "bc", "abc".
The string "abcd" is not consistent because it contains the character 'd' which is not in `allowed`.

Approach:

  1. Convert allowed string to a set for O(1) lookup time.
  2. Iterate over each word in the words array and check if all characters in that word exist in the allowed set.
  3. Count the words that are consistent.

Code Implementation:

function countConsistentStrings(allowed, words) {
    // Convert the allowed string to a Set for O(1) lookups
    const allowedSet = new Set(allowed);
    let count = 0;

    // Iterate over each word in the words array
    for (let word of words) {
        let isConsistent = true;

        // Check if every character in the word is in the allowed set
        for (let char of word) {
            if (!allowedSet.has(char)) {
                isConsistent = false;
                break;
            }
        }

        // If the word is consistent, increment the count
        if (isConsistent) {
            count++;
        }
    }

    return count;
}

// Example usage
const allowed = "abc";
const words = ["a","b","c","ab","ac","bc","abc","abcd"];
console.log(countConsistentStrings(allowed, words)); // Output: 7

Explanation:

  1. We first convert the allowed string into a set allowedSet to make it easy to check if each character of the words is in allowed.
  2. For each word, we check whether all its characters exist in allowedSet.
  3. If a word is consistent, we increment the count variable.
  4. Finally, the function returns the total count of consistent strings.

This solution has a time complexity of O(n * m), where n is the number of words, and m is the average length of the words, which is efficient enough for typical input sizes.

Leave a Reply