Count available letters once, count each word, and include the word only when every required frequency is available.
Complexity
O(c + total word characters) time and O(1) counter space.
Sum the lengths of words constructible from a shared multiset of available characters.
Count available letters once, count each word, and include the word only when every required frequency is available.
O(c + total word characters) time and O(1) counter space.
package main
func countCharacters(words []string, chars string) int {
var available [26]int
for _, character := range chars {
available[character-'a']++
}
total := 0
for _, word := range words {
var count [26]int
for _, character := range word {
count[character-'a']++
}
valid := true
for index, needed := range count {
if needed > available[index] {
valid = false
break
}
}
if valid {
total += len(word)
}
}
return total
}
from collections import Counter
class Solution:
def countCharacters(self, words: list[str], chars: str) -> int:
available = Counter(chars)
return sum(len(word) for word in words if not (Counter(word) - available))
function countCharacters(words: string[], chars: string): number {
const available = new Array<number>(26).fill(0); for (const character of chars) available[character.charCodeAt(0) - 97] += 1;
let total = 0;
for (const word of words) { const count = new Array<number>(26).fill(0); for (const character of word) count[character.charCodeAt(0) - 97] += 1; if (count.every((needed, index) => needed <= available[index])) total += word.length; }
return total;
}