Given a bag of characters, find the total length of all words that can be formed using each character at most as many times as it appears.
You are given an array of words and a string of available characters. A word is good if every character in the word can be taken from the available characters without reusing any character more times than it appears in the string.
Return the sum of the lengths of all good words.
A character may be used at most once per occurrence in the given character string. Each word is checked independently against the same character supply.
Compute the total length of all words that can be formed under these constraints.
words: an array of lowercase wordschars: a lowercase string representing the available characterschars.1 <= words.length is typically up to the low thousandschars contain only lowercase English lettersExample 1
Input
words = ["cat","bt","hat","tree"], chars = "atach"
Output
6
Explanation
"cat" and "hat" can be formed, so the total is 3 + 3 = 6.
Example 2
Input
words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output
10
Explanation
"hello" and "world" can be formed. Their lengths are 5 and 5, so the sum is 10.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.