You are given an array of strings words and a string chars.
A string in words is considered good if it can be formed using only the characters available in chars, where each character in chars may be used at most once per word.
Return the sum of the lengths of all good strings in words.
Constraints:
words.length
words[i].length, chars.length
words[i] and chars consist of lowercase English letters.
The key intuition behind this solution is that we only care about character availability and frequency, not character order. A word can be formed from chars only if every letter it needs is present in chars with at least the same count. Because of this, frequency counting is the most direct way to solve the problem.
We first create a frequency map for chars to record how many times each character is available. Then, for each word, we count its characters and compare those counts with the ones in chars. If all required characters are available in sufficient quantity, the word is good, and we add its length to the answer.
Now, let’s look at the solution steps below:
Build a frequency map charsCount from the string chars using a Counter. This maps each character to the number of times it appears in chars.
Initialize a variable totalLength to
You are given an array of strings words and a string chars.
A string in words is considered good if it can be formed using only the characters available in chars, where each character in chars may be used at most once per word.
Return the sum of the lengths of all good strings in words.
Constraints:
words.length
words[i].length, chars.length
words[i] and chars consist of lowercase English letters.
The key intuition behind this solution is that we only care about character availability and frequency, not character order. A word can be formed from chars only if every letter it needs is present in chars with at least the same count. Because of this, frequency counting is the most direct way to solve the problem.
We first create a frequency map for chars to record how many times each character is available. Then, for each word, we count its characters and compare those counts with the ones in chars. If all required characters are available in sufficient quantity, the word is good, and we add its length to the answer.
Now, let’s look at the solution steps below:
Build a frequency map charsCount from the string chars using a Counter. This maps each character to the number of times it appears in chars.
Initialize a variable totalLength to