Python 1160.py
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
freq = defaultdict(int)
for c in chars:
freq[c] += 1
result = 0
for w in words:
have = freq.copy()
ok = True
# "consume" letters
for c in w:
# running out of letters
if c not in have or have[c] == 0:
ok = False
break
have[c] -= 1
# valid
if ok:
result += len(w)
return result
Difficulty
and has an acceptance rate of about 71% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- String
AI Disclaimer
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.
Code Walkthrough
Overview
The implementation defines a method that receives a list of words and a string of available characters. It computes the total length of all words that can be formed using the characters, respecting the count of each character. The algorithm builds a frequency map of the characters, then iterates through each word, checking whether the word can be assembled by “consuming” characters from a copy of that map. If a word passes the check, its length contributes to the final sum.
Key Steps
Building the character frequency table
The first phase creates a dictionary that records how many times each character appears in the input string.
freq = defaultdict(int)
for c in chars:
freq[c] += 1
Using a defaultdict eliminates the need for explicit existence checks when incrementing counts, providing constant-time updates.
Iterating over the words
The algorithm initializes an accumulator for the result and then processes each word in the list.
result = 0
for w in words:
have = freq.copy()
ok = True
A shallow copy of the frequency table is made for each word, ensuring that the original counts remain unchanged for subsequent words.
Consuming characters while validating a word
For each character in the current word, the code verifies that the character is still available in the copied table. If a character is missing or its count has dropped to zero, the word is marked as invalid and the inner loop exits early.
for c in w:
if c not in have or have[c] == 0:
ok = False
break
have[c] -= 1
The early break prevents unnecessary processing once a deficit is detected, which is especially beneficial for long words that cannot be formed.
Accumulating the length of valid words
After the inner loop finishes, the algorithm adds the word’s length to the total only when the word passed the validation step.
if ok:
result += len(w)
Finally, the accumulated sum is returned.
return result
Edge Cases Handled
When the character string is empty, the frequency table contains no entries, causing every word to fail the availability test immediately; the result remains zero.
If the list of words is empty, the outer loop never executes, and the method returns zero without performing any work.
Words that contain characters not present in the frequency table trigger the c not in have condition, leading to an early exit for that word.
Words that require more occurrences of a particular character than are available are caught by the have[c] == 0 check, ensuring that over-consumption is prevented.
Single-character words and words composed entirely of repeated characters are correctly processed because the copy of the frequency map tracks decrementing counts for each occurrence.
Performance Optimizations
The use of a defaultdict for the initial frequency construction provides fast insertion without conditional logic.
Copying the frequency dictionary once per word (freq.copy()) avoids rebuilding the map from scratch for each validation, reducing overhead when the list of words is large.
The inner loop includes an early termination condition (break) as soon as a missing or exhausted character is detected, which saves time for words that cannot be formed early in their character sequence.
Updating the result only after a word passes all checks prevents unnecessary arithmetic operations for invalid words.
Overall, the design minimizes redundant work by reusing the pre-computed frequency table, leveraging constant-time dictionary operations, and short-circuiting on failure conditions.
ELI5 - Simplified Explanation
Imagine having a big box filled with lots of colorful letter blocks. You also have a list of secret words you want to build using only the blocks inside your box.
First, the code looks at all the letters in the box and keeps a tally of them so it knows exactly how many of each letter are available. This is like counting up your pile of blocks to see how many A's, B's, and C's you have ready to go.
Next, the code goes through the list of words one by one. For every word, it pretends to take the blocks it needs out of the box. If it finds a letter it needs, it subtracts that block from the pile. If it ever needs a letter that is already used up or was never in the box to begin with, it knows that word cannot be built.
If the word can be successfully built using the blocks, the code measures how long that word is by counting its letters. It keeps a running total of the lengths of every word that could be made. This helps determine the final amount of blocks used for all the possible words.
Code Quality
Complexity Analysis
Other Solutions
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++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Go | PHP | TS | ||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | JS | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | JavaScript | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 383: Ransom Note
- problem 2287: Rearrange Characters to Make Target String
Solved On The Same Day
- problem 1103: Distribute Candies to People
- problem 1122: Relative Sort Array
- problem 1080: Insufficient Nodes in Root to Leaf Paths
- problem 1138: Alphabet Board Path
- problem 1162: As Far from Land as Possible
- problem 1921: Eliminate Maximum Number of Monsters
- problem 1178: Number of Valid Words for Each Puzzle
Extra
- 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