VOOZH about

URL: https://www.geeksforgeeks.org/dsa/counting-common-prefix-suffix-strings-in-two-lists/

⇱ Counting common prefix/suffix strings in two lists - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Counting common prefix/suffix strings in two lists

Last Updated : 4 Jun, 2026

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.

[Naive Approach] Check Every String Pair - O(|s1| * |s2| * L) Time O(1) Space

The idea is to check every string of s2 against every string of s1. For each pair of strings, we verify whether the string from s2 occurs as a prefix or as a suffix of the string from s1. If either condition is satisfied for at least one string in s1, we count that string from s2 in the answer.


Output
4

Time Complexity: O(|s1| * |s2| * L)
Auxiliary Space: O(1)

[Expected Approach] Trie-Based Prefix and Suffix Matching - O((n + m) * L) Time O(n * L) Space

The idea is to use a Trie to efficiently store prefixes of strings. We insert every string from s1 into 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 from s1. Then, for each string in s2, 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:

  • Build a Trie by inserting every string from s1, so that every traversable path from the root represents a prefix of some string in s1.
  • To support suffix matching, also insert the reversed form of every string from s1 into the same Trie.
  • For each string 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.
  • Also reverse 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.
  • Count every string in s2 for which either the prefix check or the suffix check succeeds.

Output
4

Time Complexity: O((n + m) * L)
Auxiliary Space: O(n * L)

Comment
Article Tags: