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", (1,2) "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 I INPUT String Array: words[] "a" i=0 "aba" i=1 "ababa" i=2 "aa" i=3 isPrefixAndSuffix(str1, str2) Returns true if str1 is BOTH prefix AND suffix of str2 Find pairs (i,j) where i < j and function returns true ALGORITHM STEPS 1 Length Check Skip if len(str1) > len(str2) 2 Prefix Check str2.startsWith(str1) 3 Suffix Check str2.endsWith(str1) 4 Count Valid Pairs Increment if both true Valid Pairs Found: (0,1): "a" in "aba" OK (0,2): "a" in "ababa" OK (0,3): "a" in "aa" OK (1,2): "aba" in "ababa" OK (1,3): "aba" in "aa" NO (2,3): "ababa" in "aa" NO FINAL RESULT Valid Pairs Count 4 Matching Pairs: (0,1) (0,2) (0,3) (1,2) Output: 4 Key Insight: Length-Based Optimization Before checking prefix/suffix, verify len(str1) <= len(str2). This early termination skips impossible pairs immediately. For each valid pair, str1 must appear at both the start AND end of str2. Time Complexity: O(n^2 * m) where n = array length, m = max string length. TutorialsPoint - Count Prefix and Suffix Pairs I | Length-Based Optimization Approach
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