Count Prefix and Suffix Pairs II - Problem

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) returns true if str1 is both a prefix and a suffix of str2, and false otherwise.

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.

Input & Output

Example 1 — Basic Case
$ Input: words = ["a","aba","ababa","aa"]
Output: 4
💡 Note: Valid pairs: (0,1) "a" is prefix/suffix of "aba", (0,2) "a" is prefix/suffix of "ababa", (0,3) "a" is prefix/suffix of "aa", (1,2) "aba" is prefix/suffix of "ababa"
Example 2 — No Matches
$ Input: words = ["pa","papa","ma","mama"]
Output: 2
💡 Note: Valid pairs: (0,1) "pa" is prefix/suffix of "papa", (2,3) "ma" is prefix/suffix of "mama"
Example 3 — Edge Case
$ Input: words = ["abab","ab"]
Output: 0
💡 Note: No valid pairs since "abab" cannot be prefix/suffix of shorter "ab"

Constraints

  • 1 ≤ words.length ≤ 5 × 104
  • 1 ≤ words[i].length ≤ 105
  • words[i] consists only of lowercase English letters
  • The sum of lengths of all words[i] does not exceed 5 × 105

Visualization

Tap to expand
Count Prefix and Suffix Pairs II"a""aba""ababa""aa"i=0i=1i=2i=3Valid Pairs Found:(0,1): "a" prefix/suffix of "aba"(0,2): "a" → "ababa"(1,2): "aba" → "ababa"Result: 4 pairs
Understanding the Visualization
1
Input
Array of strings ["a", "aba", "ababa", "aa"]
2
Check Pairs
For each pair (i,j) where i < j, check prefix and suffix condition
3
Count Matches
Count pairs where words[i] is both prefix and suffix of words[j]
Key Takeaway
🎯 Key Insight: A string can only be both prefix and suffix if it appears at the beginning and end of another string
Asked in
Google 15 Facebook 12 Amazon 8
2.5K Views
Medium Frequency
~35 min Avg. Time
89 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