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 of 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 <= 501 <= words[i].length <= 10words[i]consists only of lowercase English letters.
Approach 01:
-
C++
-
Python
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
// Helper function to check if str1 is both a prefix and suffix of str2
int isPrefixAndSuffix(string& prefixSuffixCandidate, string& targetString) {
long long candidateLength = prefixSuffixCandidate.length();
long long targetLength = targetString.length();
// Extract the prefix and suffix from the target string
string prefix = targetString.substr(0, candidateLength);
string suffix = targetString.substr(targetLength - candidateLength, candidateLength);
// Check if both the prefix and suffix match the candidate string
if (prefix == prefixSuffixCandidate && suffix == prefixSuffixCandidate) {
return 1;
}
return 0;
}
// Count all valid prefix-suffix pairs
int countPrefixSuffixPairs(vector<string>& words) {
long long totalWords = words.size();
long long validPairCount = 0;
// Iterate over all pairs of strings
for (int i = 0; i < totalWords - 1; ++i) {
for (int j = i + 1; j < totalWords; ++j) {
// Check if the first word can be a prefix and suffix of the second word
if (words[i].length() <= words[j].length()) {
validPairCount += isPrefixAndSuffix(words[i], words[j]);
}
}
}
return validPairCount;
}
};
class Solution:
# Helper function to check if str1 is both a prefix and suffix of str2
def isPrefixAndSuffix(self, prefixSuffixCandidate, targetString):
candidateLength = len(prefixSuffixCandidate)
targetLength = len(targetString)
# Extract the prefix and suffix from the target string
prefix = targetString[:candidateLength]
suffix = targetString[targetLength - candidateLength:]
# Check if both the prefix and suffix match the candidate string
if prefix == prefixSuffixCandidate and suffix == prefixSuffixCandidate:
return 1
return 0
# Count all valid prefix-suffix pairs
def countPrefixSuffixPairs(self, words):
totalWords = len(words)
validPairCount = 0
# Iterate over all pairs of strings
for i in range(totalWords - 1):
for j in range(i + 1, totalWords):
# Check if the first word can be a prefix and suffix of the second word
if len(words[i]) <= len(words[j]):
validPairCount += self.isPrefixAndSuffix(words[i], words[j])
return validPairCount
Time Complexity:
- Outer Loop:
The outer loop iterates over all pairs of words, leading to \( O(n^2) \), where \( n \) is the number of words in
words. - Substring Operations:
For each pair, the
substrfunction is called twice, which takes \( O(m) \), where \( m \) is the length of the candidate string. - String Comparison:
Each comparison of prefix and suffix strings also takes \( O(m) \).
- Overall Time Complexity:
\( O(n^2 \cdot m) \), where \( n \) is the number of words, and \( m \) is the average length of the strings in
words.
Space Complexity:
- Auxiliary Space for Strings:
The
substrfunction creates new strings for prefix and suffix comparisons, requiring \( O(m) \) additional space for each call. - Overall Space Complexity:
\( O(m) \), where \( m \) is the length of the longest string being processed.