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.
Problem
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.
Goal
Compute the total length of all words that can be formed under these constraints.
Input Format
words: an array of lowercase wordschars: a lowercase string representing the available characters
Output Format
- Return a single integer: the sum of lengths of all words that can be formed from
chars.
Constraints
1 <= words.lengthis typically up to the low thousands- Words and
charscontain only lowercase English letters - Exact official constraints may vary by platform; use frequency counting to solve efficiently
Example 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
Unlock deeper context for this problem
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.