counter
string
]
Leetcode 0916. Word Subsets
https://leetcode.com/problems/word-subsets
The idea here is to use counters: we need to find elements from A, for which each string from B have less or equal frequencies for each symbol. Let us create cnt: counter, with maximal values for each letter, that is if we have B = [abb, bcc], then we have cnt = {a:1, b:2 ,c:2}. In python it can be written using | symbol.
Second step is for each string a from A calcuate counter and check that it is bigger for each element than cnt. Again in python it can be don in very short way, using not cnt - Counter(a).
Complexity: time complexity is O(m + n), where m is total length of words in A and m is total length of words in n. Space complexity is O(m), because potentially answe can consist all strings from A.
class Solution:
def wordSubsets(self, A, B):
cnt = Counter()
for b in B:
cnt |= Counter(b)
return [a for a in A if not cnt - Counter(a)]
If you like the solution, you can upvote it on leetcode discussion section: Problem 0916