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.
Example 1:
Output: 6
Explanation: Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Algorithm:
- Initialize an array
arrof size 26 to represent the count of each lowercase letter in thecharsstring. - Iterate through each character in the
charsstring and update the count in thearrarray. - Initialize a variable
ansto store the total length of words that can be formed. - Iterate through each word in the
wordsarray.- Initialize an array
arr_of size 26 to represent the count of each lowercase letter in the current words. - Initialize a boolean variable
canMadetotrue. - Iterate through each character in the current word
sand update the count in thearr_array. - Check if there are enough available characters in
charsto form the word. If not, setcanMadetofalseand break out of the loop. - If
canMadeis stilltrueafter the inner loop, add the length of the current wordsto theansvariable.
- Initialize an array
- Return the total length of words that can be formed using the characters in
chars(stored in theansvariable).
Code Implementation:
Output:
6
Complexity Analysis:
Time Complexity: O(N + M * K),
1. The first loop that iterates through the characters in the chars string has a time complexity of O(N), where N is the length of the chars string.
2. The second loop iterates through each word in the words array, and for each word, it iterates through its characters. Let M be the maximum length of a word in the words array. Therefore, the time complexity of this part is O(M * K), where K is the number of words in the array.
Overall, the time complexity of the code is O(N + M * K).
Space Complexity:O(K),
1. The code uses an array arr of size 26 to store the count of characters in the chars string. Therefore, the space complexity for this part is O(26), which simplifies to O(1).
2. Inside the second loop, the code creates an array arr_ for each word, which is also of size 26. So, the space complexity for this part is O(26 * K), where K is the number of words in the array.
Therefore, the overall space complexity of the code is O(1 + 26 * K), which simplifies to O(K) since K is typically much smaller than the other parameters.
If you want to contribute such articles to solutions2coding.com please click here. Thank you!
2025’s software development costs are shifting – stay ahead with this detailed breakdown. Highly recommended!Explore the A Complete Guide to the Software Development Cost 2025
ReplyDeleteBrisbane's leading ecommerce app developers - We craft mobile shopping experiences that outperform websites. Features include wishlists, instant search, and secure payment gateways to maximize your revenue. Book a free strategy session! App Developers Brisbane
ReplyDelete