Total length of string from given Array of strings composed using given characters
Last Updated :
31 Oct, 2021
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++
// 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;
}
Java
// 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
Python3
# 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
C#
// C# implementation to find total length
// of string composed of given characters
// formed from given Array of strings
using System;
using System.Collections.Generic;
using System.Linq;
class GFG{
// Function to count the total length
static int countCharacters(List<string> strings,
string chars)
{
int res = 0;
// Dictionary for keeping frequency
// of characters
Dictionary<char,
int> freq = new Dictionary<char,
int>();
// Calculate the frequency
for(int i = 0; i < chars.Length; i++)
{
if(freq.ContainsKey(chars[i]))
{
freq[chars[i]]++;
}
else
{
freq.Add(chars[i],
freq.GetValueOrDefault(
chars[i], 0) + 1);
}
}
// Iterate in the N strings
foreach(string st in strings)
{
bool flag = true;
// Iterates in the string
foreach (char c in 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)
{
string []tmp = { "hi", "data",
"geeksforgeeks" };
List<string> strings = tmp.ToList();
string chars = "tiadhae";
Console.Write(countCharacters(strings, chars));
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// Javascript implementation to find total length
// of string composed of given characters
// formed from given Array of strings
// Function to count the total length
function countCharacters( strings, chars)
{
var res = 0;
// Unordered_map for
// keeping frequency of characters
var freq = new Map();
// Calculate the frequency
for (var i = 0; i < chars.length; i++)
{
if(freq.has(chars[i]))
freq.set(chars[i], freq.get(chars[i])+1)
else
freq.set(chars[i], 1)
}
// Iterate in the N strings
strings.forEach(st => {
var flag = true;
// Iterates in the string
st.split('').forEach(c => {
// Checks if given character of string
// string appears in it or not
if (!freq.has(c)) {
flag = false;
}
});
// Adds the length of string
// if all characters are present
if (flag)
res += st.length;
});
// Return the final result
return res;
}
// Driver code
var strings
= ["hi", "data",
"geeksforgeeks"];
var chars = "tiadhae";
document.write( countCharacters(strings, chars));
// This code is contributed by noob2000.
</script>
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 unordered map will be of size 26 only.
Similar Reads
Count of strings that does not contain any character of a given string Given an array arr containing N strings and a string str, the task is to find the number of strings that do not contain any character of string str. Examples: Input: arr[] = {"abcd", "hijk", "xyz", "ayt"}, str="apple"Output: 2Explanation: "hijk" and "xyz" are the strings that do not contain any char
8 min read
Count of substrings formed using a given set of characters only Given a string str and an array arr[] of K characters, the task is to find the number of substrings of str that contain characters only from the given character array arr[]. Note: The string str and the arr[] contain only lowercase alphabets. Examples: Input: S = "abcb", K = 2, charArray[] = {'a', '
8 min read
Count strings from given array having all characters appearing in a given string Given an array of strings arr[][] of size N and a string S, the task is to find the number of strings from the array having all its characters appearing in the string S. Examples: Input: arr[][] = {"ab", "aab", "abaaaa", "bbd"}, S = "ab"Output: 3Explanation: String "ab" have all the characters occur
6 min read
All possible strings of any length that can be formed from a given string Given a string of distinct characters, print all possible strings of any length that can be formed from given string characters. Examples: Input: abcOutput: a b c abc ab ac bc bac bca cb ca ba cab cba acbInput: abcdOutput: a b ab ba c ac ca bc cb abc acb bac bca cab cba d ad da bd db abd adb bad bda
10 min read
Maximize length of the String by concatenating characters from an Array of Strings Find the largest possible string of distinct characters formed using a combination of given strings. Any given string has to be chosen completely or not to be chosen at all. Examples: Input: strings ="abcd", "efgh", "efgh" Output: 8Explanation: All possible combinations are {"", "abcd", "efgh", "abc
12 min read
Smallest string containing all unique characters from given array of strings Given an array of strings arr[], the task is to find the smallest string which contains all the characters of the given array of strings. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanation: The string "ruyo" is the smallest string which contains all the characters that are u
9 min read
Find frequency of each character with positions in given Array of Strings Given an array, arr[] consisting of N strings where each character of the string is lower case English alphabet, the task is to store and print the occurrence of every distinct character in every string. Examples:Â Input: arr[] = { "geeksforgeeks", "gfg" }Output: Occurrences of: e = [1 2] [1 3] [1 1
7 min read
Create a string with unique characters from the given N substrings Given an array arr[] containing N substrings consisting of lowercase English letters, the task is to return the minimum length string that contains all given parts as a substring. All characters in this new answer string should be distinct. If there are multiple strings with the following property p
11 min read
Count of Substrings that can be formed without using the given list of Characters Given a string str and a list of characters L, the task is to count the total numbers of substrings of the string str without using characters given in the list L. Examples: Input: str = "abcd", L[] = {'a', 'b', 't', 'q'} Output: 3 Explanation: On ignoring the characters 'a' and 'b' from the given s
7 min read
Print all valid words from given dictionary that are possible using Characters of given Array Given a dictionary of strings dict[] and a character array arr[]. The task is to print all valid words of the dictionary that are possible using characters from the given character array.Examples:Input: dict[] = ["go", "bat", "me", "eat", "goal", boy", "run"] , arr[] = ['e', 'o', 'b', 'a', 'm', 'g',
7 min read