Count of strings in Array A that can be made equal to strings in Array B by appending characters
Given two arrays of strings SearchWord[] and FindWord[]. The task is to check how many strings in FindWord[] can be formed after the following operations on as many strings as possible:
- Pick a string from SearchWord[].
- Add one English alphabet (that is not present in that string).
- Rearrange the string as you like.
Note: Every alphabet in the SearchWord[] and in the FindWord[] are unique and appear only once.
Examples:
Input: SearchWord = {“ge”, “fo”, “ek”}, FindWord = {“gek”, “for”}
Output: 2
Explaination: ‘k’ can be appended to the “ge” to make “gek” which matches the FindWord[0]
‘r’ can be appended to the “fo” to make “for” which matches the FindWord[1]Input: SearchWord = {“ohr”, “tm”, “ek”}, FindWord = {“mat”, “hr”}
Output: 1
Approach: The simple approach to solving this problem is by sorting and using hashing technique.
- Sort SearchWord[] and FindWord[] in Alphabetical order.
- Apply the reverse logic rather than picking a word from the SearchWord[] array, pick the word from the FindWord[] array.
- And search that word by removing the character one by one and finding the Matching word.
Below is the implementation of the above approach.
C++
// C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to find permutationint solution(vector<string>& sw, vector<string>& tw){ unordered_set<string> s; for (int i = 0; i < sw.size(); i++) { sort(sw[i].begin(), sw[i].end()); s.insert(sw[i]); } int ans = 0; // Loop to check how many string // can be formed for (int i = 0; i < tw.size(); i++) { string test = tw[i]; sort(test.begin(), test.end()); // To track the number // Of the words formed bool check = 0; for (int j = 0; j < test.size(); j++) { // Substring from 0 to 'i' // and remove one alphabet // and append rest of the string string search = test.substr(0, j) + test.substr(j + 1); // Check if the word is available // in the set if (s.find(search) != s.end()) { check = 1; break; } } if (check) ans++; } return ans;} // Driver Codeint main(){ vector<string> str = { "ohr", "tm", "ek" }; vector<string> str1 = { "mat", "hr" }; cout << solution(str, str1); return 0;} |
1
Time Complexity: O(N*M) where N and M are the size of SearchWord[] and FindWord[]
Auxiliary Space: O(N)


 (2).jpg)