Similar Problems

Similar Problems not available

Find Words That Can Be Formed By Characters - Leetcode Solution

Companies:

LeetCode:  Find Words That Can Be Formed By Characters Leetcode Solution

Difficulty: Easy

Topics: string hash-table array  

Problem Statement:

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:

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.

Solution:

To solve this problem, we can iterate over each word in the words array and check if it can be formed using the characters in the chars string.

For each word, we can create a hashmap to keep a count of each character in the word. Then, we can iterate over the characters in the chars string and check if each character is present in the hashmap and its count is greater than 0. If it is, we decrement the count in the hashmap and continue iterating. If not, we break out of the loop and move onto the next word in the words array.

If we successfully iterate over all characters in the chars string for a word, it means that the word can be formed using the given characters. In this case, we add the length of the word to a running total.

At the end, we return the running total as the result.

Code:

Here is the code for the solution described above:

class Solution {
    public int countCharacters(String[] words, String chars) {
        int result = 0;
        int[] charCounts = new int[26];
        for(char c : chars.toCharArray()) {
            charCounts[c - 'a']++;
        }
        for(String word : words) {
            int[] wordCounts = new int[26];
            for(char c : word.toCharArray()) {
                wordCounts[c - 'a']++;
            }
            boolean canFormWord = true;
            for(int i=0; i<26; i++) {
                if(wordCounts[i] > charCounts[i]) {
                    canFormWord = false;
                    break;
                }
            }
            if(canFormWord) {
                result += word.length();
            }
        }
        return result;
    }
}

Time Complexity:

The time complexity of this algorithm is O(N*M), where N is the number of words in the words array and M is the length of the longest word in the array. We iterate over each character in the chars string once and each character in each word in the words array once.

Space Complexity:

The space complexity of this algorithm is O(1) because we are using constant space for the character count arrays.

Find Words That Can Be Formed By Characters Solution Code

1