# Number of strings in two array satisfy the given conditions

Given two arrays of string arr1[] and arr2[]. For each string in arr2[](say str2), the task is to count numbers string in arr1[](say str1) which satisfy the below conditions:

• The first characters of str1 and str2 must be equal.
• String str2 must contain each character of string str1.

Examples:

Input: arr1[] = {“aaaa”, “asas”, “able”, “ability”, “actt”, “actor”, “access”}, arr2[] = {“aboveyz”, “abrodyz”, “absolute”, “absoryz”, “actresz”, “gaswxyz”}
Output:

Explanation:
The following is the string in arr1[] which follows the given condition:
1 valid word for “aboveyz” : “aaaa”.
1 valid word for “abrodyz” : “aaaa”.
3 valid words for “absolute” : “aaaa”, “asas”, “able”.
2 valid words for “absoryz” : “aaaa”, “asas”.
4 valid words for “actresz” : “aaaa”, “asas”, “actt”, “access”.
There are no valid words for “gaswxyz” because none of the words in the list contains the letter ‘g’.

Input: arr1[] = {“abbg”, “able”, “absolute”, “abil”, “actresz”, “gaswxyz”}, arr2[] = {“abbgaaa”, “asas”, “able”, “ability”}
Output:

1

Brute Force Approach: This approach uses a nested loop to iterate through each string in arr1 and arr2, and checks if the first character of each string in arr1 matches the first character of the string in arr2.

Step by step algorithm:

1. Initialize an empty vector of integers called result to store the count of valid strings.
2. For each string str2 in arr2, do the following:
a. Initialize a counter variable called count to 0.
b. For each string str1 in arr1, do the following:
i. Check if the first character of str1 is equal to the first character of str2.
ii. If they are equal, iterate over each character c in str1, and check if it is present in str2 using the find() function.
iii. If all characters of str1 are present in str2, increment the count.
c. Add the final count to the result vector.
3. Return the result vector.

Below is the implementation of above approach:

## C++

 #include #include #include   using namespace std;   vector count_strings(vector arr1, vector arr2) {     vector result;     for (string str2 : arr2) {         int count = 0;         for (string str1 : arr1) {             if (str1[0] == str2[0]) {                 bool flag = true;                 for (char c : str1) {                     if (str2.find(c) == string::npos) {                         flag = false;                         break;                     }                 }                 if (flag) {                     count++;                 }             }         }         result.push_back(count);     }     return result; }   int main() {     vector arr1 = {"aaaa", "asas", "able", "ability", "actt", "actor", "access"};     vector arr2 = {"aboveyz", "abrodyz", "absolute", "absoryz", "actresz", "gaswxyz"};     vector result = count_strings(arr1, arr2);     for (int i : result) {         cout << i << "\n";     }     return 0; }

## Java

 import java.util.ArrayList; import java.util.List;   public class StringCounter {     // Function to count strings in arr1 that are compatible     // with each string in arr2     public static List     countStrings(List arr1, List arr2)     {         List result             = new ArrayList<>(); // List to store the counts                                  // for each arr2 string         for (String str2 :              arr2) { // Loop through each string in arr2             int count = 0; // Counter for compatible strings                            // in arr1             for (String str1 :                  arr1) { // Loop through each string in arr1                 if (str1.charAt(0)                     == str2.charAt(                         0)) { // Check if the first                               // character matches                     boolean flag = true; // Flag to track                                          // compatibility                     for (char c :                          str1.toCharArray()) { // Loop                                                // through                                                // each                                                // character                                                // in str1                         if (str2.indexOf(c)                             == -1) { // Check if character                                      // is not in str2                             flag = false; // Set flag to                                           // false                             break; // Exit the loop as                                    // compatibility is not                                    // possible                         }                     }                     if (flag) { // If all characters in str1                                 // are found in str2                         count++; // Increment the                                  // compatibility count                     }                 }             }             result.add(                 count); // Store the count for the current                         // str2 in the result list         }         return result; // Return the list containing counts     }       public static void main(String[] args)     {         // Input lists containing strings         List arr1             = List.of("aaaa", "asas", "able", "ability",                       "actt", "actor", "access");         List arr2             = List.of("aboveyz", "abrodyz", "absolute",                       "absoryz", "actresz", "gaswxyz");           // Call the countStrings function and store the         // result         List result = countStrings(arr1, arr2);           // Print the compatibility counts for each string in         // arr2         for (int i : result) {             System.out.println(i);         }     } }   // This code is contributed by akshitaguprzj3

## Python3

 def count_strings(arr1, arr2):     result = []     for str2 in arr2:         count = 0         for str1 in arr1:             if str1[0] == str2[0]:                 flag = True                 for c in str1:                     if c not in str2:                         flag = False                         break                 if flag:                     count += 1         result.append(count)     return result   if __name__ == '__main__':     arr1 = ["aaaa", "asas", "able", "ability", "actt", "actor", "access"]     arr2 = ["aboveyz", "abrodyz", "absolute", "absoryz", "actresz", "gaswxyz"]     result = count_strings(arr1, arr2)     for i in result:         print(i)   #code added by Avinash Wani

## C#

 using System; using System.Collections.Generic;   class GFG {     static List CountStrings(List arr1, List arr2)     {         List result = new List();         foreach (string str2 in arr2)         {             int count = 0;             foreach (string str1 in arr1)             {                 if (str1[0] == str2[0])                 {                     bool flag = true;                     foreach (char c in str1)                     {                         if (str2.IndexOf(c) == -1)                         {                             flag = false;                             break;                         }                     }                     if (flag)                     {                         count++;                     }                 }             }             result.Add(count);         }         return result;     }       static void Main()     {         List arr1 = new List { "aaaa", "asas", "able", "ability", "actt", "actor", "access" };         List arr2 = new List { "aboveyz", "abrodyz", "absolute", "absoryz", "actresz", "gaswxyz" };         List result = CountStrings(arr1, arr2);         foreach (int i in result)         {             Console.WriteLine(i);         }     } }

## Javascript

 // Define a function countStrings that takes two arrays of // strings as input and returns an array of integers. function countStrings(arr1, arr2) {     // Create an empty array to store the results.     const result = [];           // Loop through each string in arr2.     for (const str2 of arr2) {         // Initialize a count variable to keep track of matching strings.         let count = 0;                   // Loop through each string in arr1.         for (const str1 of arr1) {             // Check if the first character of str1 matches the first character of str2.             if (str1[0] === str2[0]) {                 let flag = true;                                   // Loop through each character in str1.                 for (const c of str1) {                     // Check if the character is not found in str2.                     if (str2.indexOf(c) === -1) {                         flag = false;                         break;                     }                 }                                   // If all characters in str1 are found in str2, increment the count.                 if (flag) {                     count++;                 }             }         }                   // Push the count into the result array.         result.push(count);     }           // Return the final result array.     return result; }   // Define the main function. function main() {     // Define two arrays of strings.     const arr1 = ["aaaa", "asas", "able", "ability", "actt", "actor", "access"];     const arr2 = ["aboveyz", "abrodyz", "absolute", "absoryz", "actresz", "gaswxyz"];           // Call the countStrings function and store the result.     const result = countStrings(arr1, arr2);           // Loop through the result array and print each integer on a new line.     for (const i of result) {         console.log(i);     } }   // Call the main function to start the program. main();

Output

1
1
3
2
4
0

Time Complexity: O(N^2)
Space Complexity: O(1)

Approach: This problem can be solved using the concept of Bitmasking. Below are the steps:

• Convert each string of the array arr1[] to its corresponding bitmask as shown below:
For string str = "abcd"
characters | value
a 0
b 1
c 2
d 3
As per the above characters value, the number is:
value = 20 + 21 + 23 + 24
value = 15.
so the string "abcd" represented as 15.

• Note: While bitmasking each string if the frequency of characters is more than 1, then include the corresponding characters only once.
• Store the frequency of each string in an unordered_map.
• Similarly, convert each string in the arr2[] to the corresponding bitmask and do the following:
• Instead of calculating all possible words corresponding to arr1[], use the bit operation to find the next valid bitmask using temp = (temp – 1)&val.
• It produces the next bitmask pattern, reducing one char at a time by producing all possible combinations.
• For each valid permutation, check if it validates the given two conditions and adds the corresponding frequency to the current string stored in an unordered_map to the result.

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach #include using namespace std;   void findNumOfValidWords(vector& w,                          vector& p) {     // To store the frequency of string     // after bitmasking     unordered_map m;       // To store result for each string     // in arr2[]     vector res;       // Traverse the arr1[] and bitmask each     // string in it     for (string& s : w) {           int val = 0;           // Bitmasking for each string s         for (char c : s) {             val = val | (1 << (c - 'a'));         }           // Update the frequency of string         // with it's bitmasking value         m[val]++;     }       // Traverse the arr2[]     for (string& s : p) {         int val = 0;           // Bitmasking for each string s         for (char c : s) {             val = val | (1 << (c - 'a'));         }           int temp = val;         int first = s[0] - 'a';         int count = 0;           while (temp != 0) {               // Check if temp is present             // in an unordered_map or not             if (((temp >> first) & 1) == 1) {                 if (m.find(temp) != m.end()) {                     count += m[temp];                 }             }               // Check for next set bit             temp = (temp - 1) & val;         }           // Push the count for current         // string in resultant array         res.push_back(count);     }       // Print the count for each string     for (auto& it : res) {         cout << it << '\n';     } }   // Driver Code int main() {     vector arr1;     arr1 = { "aaaa", "asas", "able",              "ability", "actt",              "actor", "access" };       vector arr2;     arr2 = { "aboveyz", "abrodyz",              "absolute", "absoryz",              "actresz", "gaswxyz" };       // Function call     findNumOfValidWords(arr1, arr2);     return 0; }

## Python3

 # Python3 program for the above approach from collections import defaultdict   def findNumOfValidWords(w, p):       # To store the frequency of string     # after bitmasking     m = defaultdict(int)       # To store result for each string     # in arr2[]     res = []       # Traverse the arr1[] and bitmask each     # string in it     for s in w:         val = 0           # Bitmasking for each string s         for c in s:             val = val | (1 << (ord(c) - ord('a')))           # Update the frequency of string         # with it's bitmasking value         m[val] += 1       # Traverse the arr2[]     for s in p:         val = 0           # Bitmasking for each string s         for c in s:             val = val | (1 << (ord(c) - ord('a')))           temp = val         first = ord(s[0]) - ord('a')         count = 0                   while (temp != 0):               # Check if temp is present             # in an unordered_map or not             if (((temp >> first) & 1) == 1):                 if (temp in m):                     count += m[temp]               # Check for next set bit             temp = (temp - 1) & val           # Push the count for current         # string in resultant array         res.append(count)           # Print the count for each string     for it in res:         print(it)   # Driver Code if __name__ == "__main__":       arr1 = [ "aaaa", "asas", "able",              "ability", "actt",              "actor", "access" ]       arr2 = [ "aboveyz", "abrodyz",              "absolute", "absoryz",              "actresz", "gaswxyz" ]       # Function call     findNumOfValidWords(arr1, arr2)   # This code is contributed by chitranayal

## Javascript



Output

1
1
3
2
4
0

Time Complexity: O(N)
Space Complexity: O(N)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!