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"cat""bt""hat""tree"Input wordschars = "atach"Available: a=2, t=1, c=1, h=1Available characters"cat" ✓ (3)"bt" ✗ (0)"hat" ✓ (3)"tree" ✗ (0)Valid wordsOutput: 3 + 3 = 6
Understanding the Visualization
1
Input
Array of words and available characters
2
Process
Check each word against available character frequencies
3
Output
Sum of lengths of valid words
Key Takeaway
🎯 Key Insight: Count character frequencies once, then check each word's requirements against available characters
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