Count Prefix and Suffix Pairs II - Problem
Count Prefix and Suffix Pairs II

You're given an array of strings called words. Your task is to find all pairs of strings where one string is both a prefix and a suffix of another string that comes later in the array.

More specifically, you need to implement a function isPrefixAndSuffix(str1, str2) that returns true if:
str1 is a prefix of str2 (appears at the beginning)
str1 is a suffix of str2 (appears at the end)

Examples:
isPrefixAndSuffix("aba", "ababa")true because "aba" appears at both the start and end of "ababa"
isPrefixAndSuffix("abc", "abcd")false because "abc" is only a prefix, not a suffix

Return the total count of valid index pairs (i, j) where i < j and isPrefixAndSuffix(words[i], words[j]) is true.

Input & Output

example_1.py — Basic Case
$ Input: ["a","aba","ababa","aa"]
Output: 4
💡 Note: Valid pairs are: (0,1) "a" is prefix/suffix of "aba", (0,2) "a" is prefix/suffix of "ababa", (0,3) "a" is prefix/suffix of "aa", and (1,2) "aba" is prefix/suffix of "ababa"
example_2.py — No Matches
$ Input: ["pa","papa","ma","mama"]
Output: 2
💡 Note: Valid pairs are: (0,1) "pa" is prefix/suffix of "papa", and (2,3) "ma" is prefix/suffix of "mama"
example_3.py — Single Characters
$ Input: ["abab","ab"]
Output: 0
💡 Note: "ab" is a prefix of "abab" but not a suffix, so no valid pairs exist

Visualization

Tap to expand
🎭 Theater Program MatchingProgram 1"a"Program 2"aba"Program 3"ababa"Program 4"aa"Matches found: "a" bookends "aba", "ababa", "aa" and "aba" bookends "ababa"🌳 Trie OptimizationBuild prefix tree to avoid checking every pairTime: O(n×m²) vs Brute Force: O(n²×m)Perfect for large datasets with many strings
Understanding the Visualization
1
Catalog Programs
Create an index of all play names and their structure
2
Pattern Matching
For each program, check if any previous play names bookend it
3
Efficient Lookup
Use the Trie structure to quickly find matching patterns
4
Count Relationships
Tally all the valid prefix-suffix relationships found
Key Takeaway
🎯 Key Insight: A string can only be both prefix and suffix if it appears at the exact beginning and end of another string. The Trie structure lets us efficiently organize and search these patterns without redundant comparisons.

Time & Space Complexity

Time Complexity
⏱️
O(n²×m)

n² for all pairs, m for string comparison operations

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
Linear Space

Constraints

  • 1 ≤ words.length ≤ 105
  • 1 ≤ words[i].length ≤ 105
  • Sum of lengths of all words ≤ 5 × 105
  • words[i] consists only of lowercase English letters
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
38.2K Views
Medium-High Frequency
~25 min Avg. Time
1.3K 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