Count Prefix and Suffix Pairs II - Problem

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) returns true if str1 is both a prefix and a suffix of str2, and false otherwise.

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.

Input & Output

Example 1 — Basic Case
$ Input: words = ["a","aba","ababa","aa"]
Output: 4
💡 Note: Valid pairs: (0,1) "a" is prefix/suffix of "aba", (0,2) "a" is prefix/suffix of "ababa", (0,3) "a" is prefix/suffix of "aa", (1,2) "aba" is prefix/suffix of "ababa"
Example 2 — No Matches
$ Input: words = ["pa","papa","ma","mama"]
Output: 2
💡 Note: Valid pairs: (0,1) "pa" is prefix/suffix of "papa", (2,3) "ma" is prefix/suffix of "mama"
Example 3 — Edge Case
$ Input: words = ["abab","ab"]
Output: 0
💡 Note: No valid pairs since "abab" cannot be prefix/suffix of shorter "ab"

Constraints

  • 1 ≤ words.length ≤ 5 × 104
  • 1 ≤ words[i].length ≤ 105
  • words[i] consists only of lowercase English letters
  • The sum of lengths of all words[i] does not exceed 5 × 105

Visualization

Tap to expand
Count Prefix and Suffix Pairs II INPUT words array: "a" i=0 "aba" i=1 "ababa" i=2 "aa" i=3 isPrefixAndSuffix(str1, str2) Returns true if str1 is BOTH prefix AND suffix of str2 Example: "aba" in "ababa" prefix: OK | suffix: OK "abc" in "abcd" suffix: NO ALGORITHM (Hash) 1 Build Z-function Trie Use (char, char) pairs as keys 2 For each word pair (i,j) where i < j, check validity 3 Hash pair encoding Combine prefix+suffix chars 4 Count valid pairs Sum matches from hash Valid Pairs Found: (0,1): "a" in "aba" OK (0,2): "a" in "ababa" OK (0,3): "a" in "aa" OK (1,2): "aba" in "ababa" OK Other pairs: No match (1,3), (2,3) fail checks FINAL RESULT Count: 4 Pair Breakdown: (0,1): "a" --> "aba" (0,2): "a" --> "ababa" (0,3): "a" --> "aa" (1,2): "aba" --> "ababa" Total valid pairs: 4 Output: 4 Key Insight: Use hash-based Trie with (prefix_char, suffix_char) pairs as keys. For string s, create keys by pairing s[i] with s[len-1-i]. This allows O(1) lookup for prefix-suffix validation. Count accumulated matches at each Trie node to efficiently find all valid (i,j) pairs in O(total_length) time complexity. TutorialsPoint - Count Prefix and Suffix Pairs II | Hash Approach
Asked in
Google 15 Facebook 12 Amazon 8
2.5K Views
Medium Frequency
~35 min Avg. Time
89 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen