FastPrepFind Words That Can Be Formed by Characters

Find Words That Can Be Formed by Characters

TabaPay logoTabaPay● EasyFULLTIMEOA

Problem statement

You are given an array of strings words and a string chars.

A word is good when it can be spelled using letters taken from chars, where each letter of chars can be used at most once in that word. Every word is checked on its own against all of chars: using letters for one word does not use them up for another word.

Return the sum of the lengths of all good words. A word that appears more than once in words counts each time it appears.

Function

countCharacters(words: String[], chars: String) → int

Examples

Example 1

words = ["pay","tab","apply","bat"]chars = "tapbay"return = 9

chars has the letters t, a, p, b, a and y. "pay", "tab" and "bat" can each be spelled from them, because every word is checked against the full set of letters on its own. "apply" needs two p and an l, but chars has one p and no l. The answer is 3 + 3 + 3 = 9.

Example 2

words = ["noon","on","moon"]chars = "onon"return = 6

chars has two o and two n. "noon" uses all four letters and "on" uses two, so both are good. "moon" needs an m, which chars does not have. The answer is 4 + 2 = 6.

Example 3

words = ["zz"]chars = "z"return = 0

"zz" needs two copies of z, but chars has only one. Each letter of chars can be used at most once in a word, so no word is good and the answer is 0.

Constraints

  • 1 <= words.length <= 1000
  • 1 <= words[i].length <= 100
  • 1 <= chars.length <= 100
  • words[i] and chars contain only lowercase English letters.
See TabaPay hiring insights
Saved
public int countCharacters(String[] words, String chars) {
    // Write your code here.
}
Checking account…