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:

  • str1 appears at the beginning of str2 (prefix)
  • str1 appears at the end of str2 (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
String Bookend VisualizationExample: "aba" and "ababa"a b a b aprefixsuffixAlgorithm StepsStep 1Check all pairs(i,j) where i < jStep 2Verify prefixwords[j].startsWith(words[i])Step 3Verify suffixwords[j].endsWith(words[i])Complexity AnalysisTime: O(n² Ɨ m) | Space: O(1)n = number of words, m = average string length
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

n
2n
⚠ Quadratic Growth
Space Complexity
O(1)

Only using a few variables for counting, no additional data structures needed

n
2n
āœ“ 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
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.5K Views
Medium Frequency
~15 min Avg. Time
850 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