Count Prefix and Suffix Pairs I (LeetCode 3042): Solution and Explanation
Count pairs i < j where words[i] is both a prefix and a suffix of words[j]. With at most 50 words of at most 10 letters, checking every pair with startswith and endswith is the clean solution. For ["a","aba","ababa","aa"] the answer is 4.
Intuition
A pair only counts when the earlier word fits on the front of the later word and also fits on the back of it.
Lay words[i] over the first letters of words[j], then over the last letters. If both overlays line up letter for letter, the pair counts.
There are at most 1225 pairs and each check touches at most 20 letters, so brute force is already fast.
Approach: Check every pair
- Set
count = 0. - For each
j, loop over every earlier indexi < j. - If
words[j]starts withwords[i]and ends withwords[i], add 1 tocount. - Return
count.
Step-by-step example
words = ["a","aba","ababa","aa"]
- j = 1,
"aba":"a"is at both ends, so (0, 1) counts. count = 1. - j = 2,
"ababa":"a"fits both ends (count = 2), and"aba"fits both ends too (count = 3). - j = 3,
"aa":"a"fits both ends (count = 4)."aba"and"ababa"are longer than"aa". - Every pair is checked, so the answer is 4.
Code: Python, Java, C++
1class Solution:
2 def countPrefixSuffixPairs(self, words: List[str]) -> int:
3 count = 0
4 for j in range(len(words)):
5 for i in range(j):
6 if words[j].startswith(words[i]) and words[j].endswith(words[i]):
7 count += 1
8 return count1class Solution {
2 public int countPrefixSuffixPairs(String[] words) {
3 int count = 0;
4 for (int j = 0; j < words.length; j++) {
5 for (int i = 0; i < j; i++) {
6 if (words[j].startsWith(words[i]) && words[j].endsWith(words[i])) {
7 count++;
8 }
9 }
10 }
11 return count;
12 }
13}1class Solution {
2public:
3 int countPrefixSuffixPairs(vector<string>& words) {
4 int count = 0;
5 for (int j = 0; j < (int) words.size(); j++) {
6 for (int i = 0; i < j; i++) {
7 const string& a = words[i];
8 const string& b = words[j];
9 if (a.size() <= b.size() && b.compare(0, a.size(), a) == 0 && b.compare(b.size() - a.size(), a.size(), a) == 0) {
10 count++;
11 }
12 }
13 }
14 return count;
15 }
16};Time and space complexity
O(n^2 * L)
There are n(n-1)/2 pairs and each prefix and suffix check compares at most L letters.
O(1)
Only the counter is stored; the built-in checks compare in place.
Other approaches
Trie of (prefix letter, suffix letter) pairs (time O(n * L), space O(n * L))
Walk each word from both ends at once, inserting the pair (w[k], w[len-1-k]) as one trie key. A node's stored count tells how many earlier words are both a prefix and a suffix. This is the approach the larger version (Part II) needs.
Z-function or hashing per word (time O(n * L), space O(n * L))
For each word, find all lengths whose prefix equals the suffix, then look those up in a hash map of earlier words. Also linear, but heavier than needed here.
Common mistakes
- Counting pairs with
i > jtoo. Only earlier words can be the prefix and suffix of a later word. - Forgetting the length check in languages without a built-in, which reads past the end of the shorter word.
- Checking only the prefix. In
["ab","abab"]the pair counts, but in["ab","abc"]it does not, because"abc"does not end with"ab".
Frequently asked questions
Can equal words form a pair?
Yes. A word is both a prefix and a suffix of itself, so two equal words at i < j always count.
Can a prefix and a suffix overlap?
Yes. In "ababa" the word "aba" is the prefix (letters 0 to 2) and the suffix (letters 2 to 4); they share the middle a, and the pair still counts.
When is brute force not enough?
In Part II, with up to 100,000 words, pairs become too many. A trie keyed on front and back letters together handles it in linear time.