Count Prefix and Suffix Pairs II Problem
Description
LeetCode Problem 3045.
You are given a 0-indexed string array words.
Let's define a boolean function isPrefixAndSuffix that takes two strings, str1 and str2:
isPrefixAndSuffix(str1, str2)returnstrueifstr1is both a prefix and a suffix ofstr2, andfalseotherwise.
For example, isPrefixAndSuffix("aba", "ababa") is true because "aba" is a prefix of "ababa" and also a suffix, but isPrefixAndSuffix("abc", "abcd") is false.
Return an integer denoting the number of index pairs (i*,* j) such that i < j, and isPrefixAndSuffix(words[i], words[j]) is true.
Example 1:
Input: words = ["a","aba","ababa","aa"]
Output: 4
Explanation: In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.
Example 2:
Input: words = ["pa","papa","ma","mama"]
Output: 2
Explanation: In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2.
Example 3:
Input: words = ["abab","ab"]
Output: 0
Explanation: In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.
Constraints:
1 <= words.length <= 10^51 <= words[i].length <= 10^5words[i]consists only of lowercase English letters.- The sum of the lengths of all
words[i]does not exceed5 * 10^5.
Solution
Approach: Trie of Character Pairs
Write each word w of length m as the sequence of pairs (w[i], w[m-1-i]) for i = 0..m-1. A word s is both a prefix and a suffix of t exactly when the pair sequence of s is a prefix of the pair sequence of t: the i-th pair of s compares s[i] with t[i] and s[len-1-i] with t[m-1-i], which is exactly what a prefix and suffix match requires.
So keep a trie whose edges are such pairs, and process the words in order. For a word, walk down the trie along its pairs. Every node on the way where an earlier word ended is a match, so add each visited node's counter to the answer. Afterwards increase the counter of the last node, which now stands for the current word.
Complexity: time O(L) and space O(L), where L is the total length of all words (store the children of a node in a hash map keyed by the pair).
class Node:
__slots__ = ["children", "cnt"]
def __init__(self):
self.children = {}
self.cnt = 0
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
ans = 0
trie = Node()
for s in words:
node = trie
for p in zip(s, reversed(s)):
if p not in node.children:
node.children[p] = Node()
node = node.children[p]
ans += node.cnt
node.cnt += 1
return ans