![]() |
VOOZH | about |
Given two arrays of strings, s1[] and s2[], count the number of strings in s2[] that occur as either a prefix or a suffix of at least one string in s1[]. Return the total count.
Examples:
Input: s1 = ["cat", "catanddog", "lion"], s2 = ["cat", "dog", "rat"]
Output: 2
Explanation:
"cat" from s2 is a prefix of "catanddog" in s1.
"dog" from s2 is a suffix of "catanddog" in s1.
"rat" is neither a prefix nor a suffix of any string in s1.
Therefore, the count is 2.
Input: s1 = ["jrjiml", "tchetn", "ucrhye", "ynayhy", "cuhffd", "cvgpoiu", "znyadv"]
s2 = ["jr", "ml", "cvgpoi", "gpoiu", "wnmkmluc", "geheqe", "uglxagyl", "uyxdroj"]
Output: 4
Explanation:
"jr" is a prefix of "jrjiml" in s1.
"ml" is a suffix of "jrjiml" in s1.
"cvgpoi" is a prefix of "cvgpoiu" in s1.
"gpoiu" is a suffix of "cvgpoiu" in s1.
The remaining strings in s2 are neither prefixes nor suffixes of any string in s1.
Therefore, the count is 4.
Table of Content
The idea is to check every string of
s2against every string ofs1. For each pair of strings, we verify whether the string froms2occurs as a prefix or as a suffix of the string froms1. If either condition is satisfied for at least one string ins1, we count that string froms2in the answer.
4
Time Complexity: O(|s1| * |s2| * L)
Auxiliary Space: O(1)
The idea is to use a Trie to efficiently store prefixes of strings. We insert every string from
s1into the Trie so that any traversable path represents a prefix of some string. To handle suffixes, we also insert the reversed form of every string froms1. Then, for each string ins2, we check whether it can be traversed in the Trie (prefix check) or whether its reversed form can be traversed in the Trie (suffix check). If either check succeeds, the string contributes to the answer.
Working of the Approach:
s1, so that every traversable path from the root represents a prefix of some string in s1. s1 into the same Trie. str in s2, check whether str can be completely traversed in the Trie. If yes, it is a prefix of at least one string in s1. str and check whether the reversed string can be traversed in the Trie. If yes, str is a suffix of at least one string in s1. s2 for which either the prefix check or the suffix check succeeds.4
Time Complexity: O((n + m) * L)
Auxiliary Space: O(n * L)