Problem 1684

Abstract / Summary

Count how many words only use allowed characters from a given set.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1684.py

class Solution:
    def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
        result = 0
        for w in words:
            result += all(c in allowed for c in w)
        return result
6 lines | 215 bytes | submitted November 14, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 83% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method countConsistentStrings. The method receives a string allowed containing characters that are permitted and a list words of candidate strings. Its purpose is to count how many of the candidate strings consist exclusively of characters found in allowed. The algorithm proceeds by iterating over each word, checking every character against the allowed set, and accumulating a total for words that satisfy the consistency condition.

Key Steps

The first step establishes a counter that will hold the final result.

result = 0

Next, the method iterates over the collection of candidate strings. For each word, it evaluates whether all characters belong to the allowed string. The all function receives a generator expression, which yields a Boolean for each character c in the current word w.

for w in words:
    result += all(c in allowed for c in w)

If the generator expression returns True for every character, all yields True, which is implicitly converted to the integer 1 when added to result. Conversely, if any character fails the membership test, all returns False, contributing 0 to the total.

Finally, the method returns the accumulated count.

return result

Edge Cases Handled

When the words list is empty, the for loop body never executes, leaving result at its initial value of 0. The method therefore correctly returns 0 without error.

If allowed is an empty string, the membership test c in allowed will always be False. Consequently, all will return False for any non-empty word, and the method will count only empty strings (if present) as consistent.

Words that contain repeated characters are processed character by character; the generator expression checks each occurrence, ensuring that duplicates do not affect the outcome beyond the basic membership test.

Empty strings within words are considered consistent because the generator expression yields no elements, and all on an empty iterable returns True by definition. Thus each empty string contributes 1 to the final count.

Performance Optimizations

The use of a generator expression inside all avoids the creation of an intermediate list that would otherwise store Boolean results for each character. This lazy evaluation reduces memory overhead, especially for long words.

The all function short-circuits as soon as it encounters a character not present in allowed. This early exit prevents unnecessary checks for the remaining characters of a word that is already known to be inconsistent, saving time when many words contain disallowed characters near the beginning.

By incrementally adding the Boolean result of all directly to result, the code eliminates an explicit conditional branch, relying on Python’s implicit conversion of True to 1 and False to 0. This concise accumulation reduces the number of executed statements inside the loop.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a special box of letter blocks that you are allowed to use. These blocks are like your allowed collection. Now, picture a big pile of words made out of other blocks sitting in front of you.

The code starts by keeping a secret count to remember how many words are okay to build. It looks at each word in the pile one by one. For every word, it checks every single letter inside it. If every letter in that word is also found in your special allowed box, then that word is perfect. When a word is perfect, the count goes up by one. After checking every word in the pile, the final number tells you how many of those words were made only from the letters you were allowed to use.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.88 | σ = 1.01

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go C Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
Krazune C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
Krazune C++
lkwq007 Python
muhammadfarhankt Go
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
32 links | 19 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

6 solutions   November 14, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality