Leetcode•Oct 05, 2026
Find Words That Can Be Formed by Characters
Hazrat Ali
Leetcode
A string is good if it can be formed by characters from chars (each character can only be used once for each word in words).
Return the sum of lengths of all good strings in words.
Example 1:
Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6 Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Example 2:
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" Output: 10 Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
Solution
var countCharacters = function(words, chars) {
const charCount = new Array(26).fill(0);
for (const ch of chars) {
charCount[ch.charCodeAt(0) - 97]++;
}
let answer = 0;
for (const word of words) {
const wordCount = new Array(26).fill(0);
let possible = true;
for (const ch of word) {
const index = ch.charCodeAt(0) - 97;
wordCount[index]++;
if (wordCount[index] > charCount[index]) {
possible = false;
break;
}
}
if (possible) {
answer += word.length;
}
}
return answer;
};