Count of Superstrings in a given array of strings
Given 2 array of strings X and Y, the task is to find the number of superstrings in X.
A string s is said to be a Superstring, if each string present in array Y is a subsequence of string s .
Examples:
Input: X = {“ceo”, “alco”, “caaeio”, “ceai”}, Y = {“ec”, “oc”, “ceo”}
Output: 2
Explanation: Strings “ceo” and “caaeio” are superstrings as each string of array Y is a subset of these 2 strings. Other strings are not included in answer all strings of array Y are not
sub-sets of them.Input: X = {“iopo”, “oaai”, “iipo”}, Y = {“oo”}
Output: 1
Approach: The idea is to use the concept of Hashing to store the frequencies of characters to solve the problem. Follow the steps below to solve the problem:
- Initialize an array of size 26 to store the maximum occurrences of every character[a-z] in each string present in array Y.
- Now consider each string s in X,
- Check if frequency of every character in s is greater than equal to the frequency obtained from the above step
Below is the implementation of the above approach:
- C++
- Java
- Python3
- C#
- Javascript
C++
// C++ implementation for the above approach #include <iostream> using namespace std; // Function to find total number of superstrings int superstring(string X[], string Y[], int N, int M) { // Array to store max frequency // Of each letter int maxFreq[26]; for ( int i = 0; i < 26; i++) maxFreq[i] = 0; for ( int j = 0; j < M; j++) { int temp[26]; for ( int i = 0; i < 26; i++) temp[i] = 0; for ( int k = 0; k < Y[j].size(); k++) { temp[Y[j][k] - 'a' ]++; } for ( int i = 0; i < 26; i++) { maxFreq[i] = max(maxFreq[i], temp[i]); } } int ans = 0; for ( int j = 0; j < N; j++) { // Array to find frequency of each letter in string // x int temp[26]; for ( int i = 0; i < 26; i++) temp[i] = 0; for ( int k = 0; k < X[j].size(); k++) { temp[X[j][k] - 'a' ]++; } int i = 0; for (i = 0; i < 26; i++) { // If any frequency is less in string x than // maxFreq, then it can't be a superstring if (temp[i] < maxFreq[i]) { break ; } } if (i == 26) { // Increment counter of x is a superstring ans++; } } return ans; } // Driver code int main() { // Size of array X int N = 4; // Size of array Y int M = 3; string X[N] = { "ceo" , "alco" , "caaeio" , "ceai" }; string Y[M] = { "ec" , "oc" , "ceo" }; cout << superstring(X, Y, N, M); // Function call return 0; } |
Java
Python3
C#
Javascript
2
Time complexity: O(N*N1 + M*M1), where N = size of array X, N1 = Maxlength(x), M = size of array Y, M1 = Maxlength(y),
Auxiliary Space: O(1)