Count Prefix and Suffix Pairs II - Problem
Count Prefix and Suffix Pairs II
You're given an array of strings called
More specifically, you need to implement a function
•
•
Examples:
•
•
Return the total count of valid index pairs
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 suffixReturn 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
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
⚠ Quadratic Growth
Space Complexity
O(1)
Only using constant extra space for variables
✓ 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code