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). Return the sum of lengths of all good strings in words
.
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
Do we need to consider the frequency of characters in chars
when forming words?
Yes, each character in chars
can only be used as many times as it appears in chars
.
Should we assume that all inputs contain only lowercase English letters?
Yes, based on the problem statement.
Count the Frequency of Characters in the chars
String:
Use Python’s collections.Counter
to count the frequency of each character in chars
.
Check Each Word:
For each word in words
, count the frequency of each character. Check if each character in the word can be formed using the characters in chars
by comparing their counts.
Sum the Lengths of Valid Words:
If a word can be formed from chars
, add its length to the sum.
chars
takes (O(C)) where (C) is the length of chars
.from collections import Counter
def countCharacters(words, chars):
# Step 1: Count the frequency of each character in chars
char_count = Counter(chars)
total_length = 0
# Step 2: Process each word in words
for word in words:
word_count = Counter(word)
# Check if the word can be formed by comparing character counts
can_form = True
for char in word_count:
if word_count[char] > char_count.get(char, 0):
can_form = False
break
# If the word can be formed, add its length to total_length
if can_form:
total_length += len(word)
return total_length
# Example usage
words = ["cat","bt","hat","tree"]
chars = "atach"
print(countCharacters(words, chars)) # Output: 6
This code correctly implements the solution by counting character frequencies and verifying each word against the available characters in chars
. The strategy ensures that we handle each word only in linear time relative to its length, making the solution efficient given the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?