Find Words That Can Be Formed by Characters

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). Return the sum of lengths of all good strings in words.

30:00

Find Words That Can Be Formed by Characters
easy
Free written solution
Topics
Companies

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). Return the sum of lengths of all good strings in words.

Example 1:
Input: {"words":["cat","bt","hat","tree"],"chars":"atach"}
Output: 6
Constraints:
  • 1≤words.length≤10001 \leq \text{words.length} \leq 1000

  • 1≤words[i].length,chars.length≤1001 \leq \text{words}[i]\text{.length}, \text{chars.length} \leq 100

  • words[i] and chars consist of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"words":["cat","bt","hat","tree"],"chars":"atach"}

Every word is checked against the full set of 5 letters in chars. First count how many copies of each letter there are.

rack from chars (bright = still free for this word, blue = taken by this word)

counting letters...

no word yet

cat

waiting

bt

waiting

hat

waiting

tree

waiting

total length of good words = 0

Variables
VariableValue
total0
DepthFunction Call
Stack empty
0/17