Count Prefix and Suffix Pairs I - Problem
Given a 0-indexed string array words, you need to find how many pairs of strings have a special relationship.
A string str1 is considered both a prefix and suffix of another string str2 if:
str1appears at the beginning ofstr2(prefix)str1appears at the end ofstr2(suffix)
Example: "aba" is both a prefix and suffix of "ababa" because:
- Prefix:
"ababa"starts with"aba" - Suffix:
"ababa"ends with"aba"
Your task is to count all valid pairs (i, j) where i < j and words[i] is both a prefix and suffix of words[j].
Input & Output
example_1.py ā Basic case with multiple matches
$
Input:
["a", "aba", "ababa", "aa"]
āŗ
Output:
4
š” Note:
Valid pairs are: (0,1) "a" is prefix and suffix of "aba", (0,2) "a" is prefix and suffix of "ababa", (0,3) "a" is prefix and suffix of "aa", and (1,2) "aba" is prefix and suffix of "ababa"
example_2.py ā No valid pairs
$
Input:
["pa", "papa", "ma", "mama"]
āŗ
Output:
2
š” Note:
Valid pairs are: (0,1) "pa" is prefix and suffix of "papa", and (2,3) "ma" is prefix and suffix of "mama"
example_3.py ā Single character strings
$
Input:
["abab", "ab"]
āŗ
Output:
0
š” Note:
No valid pairs because "abab" cannot be both prefix and suffix of "ab" (longer string cannot be prefix/suffix of shorter string)
Visualization
Tap to expand
Understanding the Visualization
1
Identify Candidates
Look for shorter strings that could potentially frame longer ones
2
Check Prefix
Verify if the shorter string appears at the beginning of the longer string
3
Check Suffix
Verify if the same shorter string appears at the end of the longer string
4
Count Matches
Increment counter for each valid prefix-suffix pair found
Key Takeaway
šÆ Key Insight: For a string to be both prefix and suffix, the target string must be at least as long and have matching characters at both ends
Time & Space Complexity
Time Complexity
O(n² à m)
We check all n² pairs, and each comparison takes O(m) time where m is the average string length
ā Quadratic Growth
Space Complexity
O(1)
Only using a few variables for counting, no additional data structures needed
ā Linear Space
Constraints
- 1 ⤠words.length ⤠50
- 1 ⤠words[i].length ⤠10
- words[i] consists only of lowercase English letters
- All strings are non-empty
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code