Find Words That Can Be Formed by Characters Problem
Description
LeetCode Problem 1160.
You are given an array of strings words and a string chars.
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.
Constraints:
1 <= words.length <= 10001 <= words[i].length, chars.length <= 100words[i]andcharsconsist of lowercase English letters.
Solution
Approach: Letter Counts
A word can be formed when, for every letter, it needs no more copies than chars has. The order of the letters does not matter, only how many of each there are.
So we count the letters of chars once in an array of 26. Then for each word we count its letters as we go; as soon as some letter is used more often than chars has it, the word is not good and we stop. If we get through the whole word, we add its length to the answer.
Each word starts with a fresh count: the letters of chars can be reused for every word, just not twice inside the same word.
Complexity: O(L) time, where L is the total length of chars and all the words, and O(1) extra space for the counts.
from collections import Counter
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
supply = Counter(chars)
ans = 0
for w in words:
need = Counter(w)
# Good if no letter is needed more often than chars has it.
if all(supply[c] >= v for c, v in need.items()):
ans += len(w)
return ans