1
class Solution {
2
public:
3
// calculate the frequency of string s
4
vector<int> giveMeFreq(string s) {
5
vector<int> freq(26, 0);
6
for (int i = 0; i < s.length(); i++) {
7
freq[s[i] - 'a']++;
8
}
9
return freq;
10
}
11

12
vector<string> wordSubsets(vector<string> &words1, vector<string> &words2) {
13
vector<string> ans; // store ans
14
vector<int> max_Freq_w2(26, 0); // store max freq of each character present in word2 stirngs
15

16
// we will Iterate over word to and try to find max freq for each character
17
// present in all strings.
18
for (auto &x : words2) {
19
vector<int> freq = giveMeFreq(x);
20
for (int i = 0; i < 26; i++) {
21
max_Freq_w2[i] = max(freq[i], max_Freq_w2[i]); // upadate freq to max freq
22
}
23
}
24

25
// we will iterate for each string in words1 ans if it have all charaters
26
// present in freq array with freq >= that then we will add it to ans
27
for (auto &x : words1) {
28
vector<int> freq = giveMeFreq(x); // gives freq of characters for word in words1
29
bool flag = true;
30
for (int i = 0; i < 26; i++) {
31
if (freq[i] < max_Freq_w2[i]) // specifies that word did not have all
32
// the characters from word2 array
33
{
34
flag = false;
35
break;
36
}
37
}
38
if (flag) ans.push_back(x); // string x is Universal string
39
}
40
return ans;
41
}
42
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0