Problem Description
Given an array of strings words and a string chars, determine which words can be formed using the characters from chars (each character can only be used once per word). Return the sum of the lengths of all such words that can be formed.
Key Insights
- Use a frequency count (hash table or fixed-size array) to count characters in chars.
- For each word, count the frequency of its characters and compare with the frequency in chars.
- Only add the word’s length to the result if every character appears enough times in chars.
Space and Time Complexity
Time Complexity: O(n * L), where n is the number of words and L is the maximum length of the words. Space Complexity: O(1) since the frequency count is limited to 26 lowercase English letters.
Solution
We start by counting the frequency of each character in the given string chars using a hash table (or fixed-size array for 26 letters). Then, for each word in words, we create a similar frequency count. We compare both counts to ensure that for each character in the word, the count needed is less than or equal to the available count in chars. If the word can be formed, we add its length to our total sum. This approach efficiently handles the constraints given.