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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code