Find Words That Can Be Formed by Characters - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
💡 Note: "cat" can be formed (c=1, a=1, t=1 all available), "bt" cannot (no 'b' in chars), "hat" can be formed (h=1, a=1, t=1 all available), "tree" cannot (need 2 'e' but chars has 0). Total length: 3 + 3 = 6
Example 2 — All Words Valid
$ Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
💡 Note: "hello" can be formed (all letters available), "world" can be formed, "leetcode" cannot be formed (missing some letters). Only "hello" (5) + "world" (5) = 10
Example 3 — No Valid Words
$ Input: words = ["dyiclysmffuhibgfvapygkorkuhn"], chars = "usdruypficfbpfbivlrhutcgvyjflhokvmcgllyderazxuxgjpxpppkxjfkdqcrxvlnxgtilxofuxnvdovgdlxihnbpanrdhpfhopgdkmahgkrr"
Output: 0
💡 Note: The single word cannot be formed with the available characters, so return 0

Constraints

  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length, chars.length ≤ 100
  • words[i] and chars consist of lowercase English letters only

Visualization

Tap to expand
Find Words That Can Be Formed by Characters INPUT words[] array: "cat" "bt" "hat" "tree" chars string: "atach" Character counts: a:2 t:1 c:1 h:1 words = ["cat","bt","hat","tree"] chars = "atach" ALGORITHM STEPS 1 Build chars frequency Count each char in chars 2 For each word: Build word frequency map 3 Compare frequencies word[c] <= chars[c] ? 4 Sum good lengths Add word.length if valid Word Check Table: Word Valid? Length "cat" OK 3 "bt" NO - "hat" OK 3 "tree" NO - FINAL RESULT Good Words Found: "cat" len = 3 "hat" len = 3 Invalid Words: "bt" no 'b' "tree" need 2 e's Calculation: len("cat") + len("hat") = 3 + 3 = 6 OUTPUT 6 Key Insight: Use frequency counting (hash map) to efficiently check if each word can be formed from chars. For each character in word, its count must be <= corresponding count in chars. Time Complexity: O(n + sum of word lengths) where n = chars.length. Space: O(1) for 26 letters. TutorialsPoint - Find Words That Can Be Formed by Characters | Most Efficient Frequency Check
Asked in
Google 25 Amazon 18
52.0K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen