NeetCode #68LC-1160EasyArrays & Hashing
← Back to All Problems#68 · #1160 · Find Words That Can Be Formed by Characters(拼写单词)
📌 Problem Statement & Constraints
You are given an array of strings
words and a string chars. A string is good if it can be formed using only the letters of chars, each letter used at most as many times as it appears in chars. Return the sum of the lengths of all good strings. Constraints: 1 <= words.length <= 1000, 1 <= chars.length <= 100, all lowercase letters.💡 Core Algorithmic Approaches
- Count the available letters in
charsonce. - For each word, count its letters and verify that no letter is required more times than available.
- If the word passes, add its length to the total.
- The whole-word check is what distinguishes this from a mere character-set test -- multiplicity matters.
💻 Benchmark Python3 Implementation
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
from collections import Counter
avail = Counter(chars)
total = 0
for w in words:
need = Counter(w)
if all(need[ch] <= avail[ch] for ch in need):
total += len(w)
return total⚡ Complexity Deep Dive
⏱️ Time Complexity
O(|chars| + sum of word lengths): each word is counted once and compared against the available letters.
💾 Space Complexity
O(k) for the two counters, with k <= 26.
⚠️ Interview Pitfalls & Follow-ups
- Checking only
set(w) <= set(chars): this ignores multiplicity, sochars = "a"would wrongly accept the word"aa". - Iterating
availinstead ofneed: you must check every letter the word needs, not every letter available. - Mutating the available counts across words: each word must be tested against the full original
chars.