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) 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 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
Count Prefix and Suffix Pairs"a""aba""ababa""aa"0123Valid Pairs Check:(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" ✓Output: 4 valid pairs
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
Asked in
Google 15 Microsoft 12
12.0K Views
Medium Frequency
~15 min Avg. Time
450 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