Total length of string from given Array of strings composed using given characters

Given a list of characters and an array of strings, find the total length of all strings in the array of strings that can be composed using the given characters.

Examples:

Input: string = [“mouse”, “me”, “bat”, “lion”], chars = “eusamotb”
Output: 10
Explanation:
The strings that can be formed using the characters “eusamotb” are “mouse” and “me” and “bat”.
Length of “mouse” is 5, length of “me” is 2, and length of “bat” is 3
Sum of all lengths = 5 + 2 + 3 = 10.

Input: string = [“hi”, “data”, “geeksforgeeks”], chars = “tiadha”
Output: 6
Explanation:
The strings that can be formed using the characters “tiadha” are “hi” and “data”. Where length of “hi” is 2, length of “data” is 4, the sum of all is 2 + 4 = 6.

Approach:



To solve the problem mentioned above we have to follow the steps given below:

  • We can use characters from the given character string that is ‘chars’ while forming a string. We can also reuse the used characters for forming the next string
  • Maintain an unordered map with character as a key and the value by keeping track of the frequency of each character from the string of chars.
  • Every time we scan characters from the list of string we reduce the frequency of character from the unordered map but we have to maintain the copy of the original map so as to check the second string .
  • If the key is not present in the map it creates one with default value as zero rather than throwing an error.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find total length
// of string composed of given characters
// formed from given Array of strings
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to count the total length
int countCharacters(
    vector<string>& strings,
    string chars)
{
    int res = 0;
  
    // Unordered_map for
    // keeping frequency of characters
    unordered_map<char, int> freq;
  
    // Calculate the frequency
    for (int i = 0; i < chars.length(); i++)
        freq[chars[i]] += 1;
  
    // Iterate in the N strings
    for (auto st : strings) {
  
        bool flag = true;
  
        // Iterates in the string
        for (auto c : st) {
  
            // Checks if given character of string
            // string appears in it or not
            if (!freq) {
                flag = false;
                break;
            }
        }
  
        // Adds the length of string
        // if all characters are present
        if (flag)
            res += st.length();
    }
  
    // Return the final result
    return res;
}
  
// Driver code
int main()
{
    vector<string> strings
        = { "hi", "data",
            "geeksforgeeks" };
  
    string chars = "tiadhae";
  
    cout << countCharacters(strings, chars);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find total length
// of string composed of given characters
// formed from given Array of strings
import java.util.*;
class GFG {
      
// Function to count the total length
static int countCharacters(List<String> strings, 
                                String chars)
{
    int res = 0;
  
    // Map for
    // keeping frequency of characters
    Map<Character, Integer> freq = new HashMap<>();
  
    // Calculate the frequency
    for (int i = 0; i < chars.length(); i++)
    {
        freq.put(chars.charAt(i),
        freq.getOrDefault(chars.charAt(i), 0) + 1);
    }
  
    // Iterate in the N strings
    for (String st : strings)
    {
        boolean flag = true;
  
        // Iterates in the string
        for (char c : st.toCharArray())
        {
  
            // Checks if given character of string
            // string appears in it or not
            if (!freq.containsKey(c)) 
            {
                flag = false;
                break;
            }
        }
  
        // Adds the length of string
        // if all characters are present
        if (flag)
            res += st.length();
    }
  
    // Return the final result
    return res;
}
  
// Driver code
public static void main(String[] args)
{
    List<String> strings = Arrays.asList("hi", "data",
                                         "geeksforgeeks");
  
    String chars = "tiadhae";
  
    System.out.println(countCharacters(strings, chars));
}
}
  
// This code is contributed by offbeat

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to find total length
# of string composed of given characters
# formed from given Array of strings
  
  
# Function to count the total length
def countCharacters(arr, chars):
    res = 0
  
    # Unordered_map for
    # keeping frequency of characters
    freq = dict()
  
    # Calculate the frequency
    for i in range(len(chars)):
        freq[chars[i]] = freq.get(chars[i], 0)+1
  
    # Iterate in the N strings
    for st in arr:
  
        flag = True
  
        # Iterates in the string
        for c in st:
  
            # Checks if given character of string
            # string appears in it or not
            if (c not in freq):
                flag = False
                break
  
        # Adds the length of string
        # if all characters are present
        if (flag):
            res += len(st)
  
    # Return the final result
    return res
  
# Driver code
if __name__ == '__main__':
    arr =["hi", "data", "geeksforgeeks"]
  
    chars = "tiadhae"
  
    print(countCharacters(arr, chars))
  
# This code is contributed by mohit kumar 29

chevron_right


Output:

6

Time Complexity: O(n * m), where n is the length of the char and m is the length of the string.

Auxiliary Space Complexity: O(1), as the undordered map will be of size 26 only.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : mohit kumar 29, offbeat