LeetCode 1684: Count the Number of Consistent Strings Solution

Master LeetCode problem 1684 (Count the Number of Consistent Strings), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1684. Count the Number of Consistent Strings

Problem Explanation

Explanation

To solve this problem, we iterate through each word in the array and check if all characters in the word are present in the allowed string. We can do this by creating a set of characters from the allowed string for faster lookup. For each word, we iterate through its characters and check if each character is in the set of allowed characters. If all characters in a word are found in the allowed set, we increment the count of consistent strings.

  • Time complexity: O(n * m) where n is the number of words and m is the average length of a word.
  • Space complexity: O(1) as the set of allowed characters has a fixed size of 26.

Solution Code

class Solution {
    public int countConsistentStrings(String allowed, String[] words) {
        int count = 0;
        Set<Character> allowedChars = new HashSet<>();
        for (char c : allowed.toCharArray()) {
            allowedChars.add(c);
        }
        
        for (String word : words) {
            boolean consistent = true;
            for (char c : word.toCharArray()) {
                if (!allowedChars.contains(c)) {
                    consistent = false;
                    break;
                }
            }
            if (consistent) {
                count++;
            }
        }
        
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1684 (Count the Number of Consistent Strings)?

This page provides optimized solutions for LeetCode problem 1684 (Count the Number of Consistent Strings) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1684 (Count the Number of Consistent Strings)?

The time complexity for LeetCode 1684 (Count the Number of Consistent Strings) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1684 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1684 in Java, C++, or Python.

Back to LeetCode Solutions