Find Words That Can Be Formed by Characters

easy hash map frequency count string

Problem

You are given an array of strings words and a string chars. A word is good if it can be formed using the letters of chars, where each letter can be used at most once. Return the sum of lengths of all good words.

Inputwords = ["cat", "bt", "hat", "tree"], chars = "atach"
Output6
"cat" (3) and "hat" (3) can be formed from "atach"; "bt" and "tree" cannot. 3 + 3 = 6.

def count_characters(words, chars):
    from collections import Counter
    avail = Counter(chars)
    total = 0
    for word in words:
        need = Counter(word)
        if all(need[c] <= avail[c] for c in need):
            total += len(word)
    return total
function countCharacters(words, chars) {
  const avail = {};
  for (const c of chars) avail[c] = (avail[c] || 0) + 1;
  let total = 0;
  for (const word of words) {
    const need = {};
    for (const c of word) need[c] = (need[c] || 0) + 1;
    let ok = true;
    for (const c in need) if (need[c] > (avail[c] || 0)) ok = false;
    if (ok) total += word.length;
  }
  return total;
}
class Solution {
    public int countCharacters(String[] words, String chars) {
        int[] avail = new int[26];
        for (char c : chars.toCharArray()) avail[c - 'a']++;
        int total = 0;
        for (String word : words) {
            int[] need = new int[26];
            for (char c : word.toCharArray()) need[c - 'a']++;
            boolean ok = true;
            for (int i = 0; i < 26; i++) if (need[i] > avail[i]) ok = false;
            if (ok) total += word.length();
        }
        return total;
    }
}
int countCharacters(vector<string>& words, string chars) {
    int avail[26] = {0};
    for (char c : chars) avail[c - 'a']++;
    int total = 0;
    for (auto& word : words) {
        int need[26] = {0};
        for (char c : word) need[c - 'a']++;
        bool ok = true;
        for (int i = 0; i < 26; i++) if (need[i] > avail[i]) ok = false;
        if (ok) total += (int)word.size();
    }
    return total;
}
Time: O(n + Σ|word|) Space: O(1)