Leetcode 1112 Solution

This article provides solution to leetcode question 1112 (find-words-that-can-be-formed-by-characters)

https://leetcode.com/problems/find-words-that-can-be-formed-by-characters

Solution

class Solution:
    def getCharFreq(self, word):
        char_freq = collections.defaultdict(int)
        for ch in word:
            char_freq[ch] += 1
        return char_freq

    def countCharacters(self, words: List[str], chars: str) -> int:
        target_char_freq = self.getCharFreq(chars)

        ans = 0
        for word in words:
            word_char_freq = self.getCharFreq(word)

            for ch, cnt in word_char_freq.items():
                if cnt > target_char_freq[ch]:
                    break
            else:
                ans += len(word)

        return ans