Count Prefix and Suffix Pairs I - 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)returnstrueifstr1is both a prefix and a suffix 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.
Input & Output
Example 1 — Basic Case
$
Input:
words = ["a","aba","ababa","aa"]
›
Output:
4
💡 Note:
Valid pairs: (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", (2,1) "aba" is prefix and suffix of "ababa". Total: 4 pairs.
Example 2 — No Valid Pairs
$
Input:
words = ["pa","papa","ma","mama"]
›
Output:
2
💡 Note:
Valid pairs: (0,1) "pa" is prefix and suffix of "papa", (2,3) "ma" is prefix and suffix of "mama". Total: 2 pairs.
Example 3 — Single Characters
$
Input:
words = ["abab","ab"]
›
Output:
0
💡 Note:
No valid pairs since "abab" is longer than "ab", and "ab" is not both prefix and suffix of "abab".
Constraints
- 1 ≤ words.length ≤ 50
- 1 ≤ words[i].length ≤ 10
- words[i] consists only of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of strings to analyze
2
Process
Check each pair (i,j) where i < j
3
Output
Count of valid prefix-suffix pairs
Key Takeaway
🎯 Key Insight: A string can only be both prefix and suffix if it appears at both ends of a longer string
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code