> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Count Prefix and Suffix Pairs II

> Tested Python solution for LeetCode 3045 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 3045, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [String](/catalog/topics/string), [Trie](/catalog/topics/trie), Rolling Hash, [String Matching](/catalog/topics/string-matching), [Hash Function](/catalog/topics/hash-function), Z Algorithm. [View on LeetCode](https://leetcode.com/problems/count-prefix-and-suffix-pairs-ii/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 3045   # by problem number
lcpy gen -s count_prefix_and_suffix_pairs_ii   # by problem name
```

## 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.

### Examples

```
Input: words = ["a","aba","ababa","aa"]
Output: 4
```

**Explanation:** The counted index pairs are (0, 1), (0, 2), (0, 3) and (1, 2).

```
Input: words = ["pa","papa","ma","mama"]
Output: 2
```

**Explanation:** The counted index pairs are (0, 1) and (2, 3).

```
Input: words = ["abab","ab"]
Output: 0
```

### Constraints

* 1 \<= words.length \<= 10^5
* 1 \<= words\[i].length \<= 10^5
* words\[i] consists only of lowercase English letters.
* The sum of the lengths of all words\[i] does not exceed 5 \* 10^5.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/count_prefix_and_suffix_pairs_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/count_prefix_and_suffix_pairs_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from typing import Any


class Solution:
    # Time: O(total chars), each character pair inserted/visited once
    # Space: O(total chars) for the paired trie
    def count_prefix_and_suffix_pairs(self, words: list[str]) -> int:
        root: dict[Any, Any] = {}
        total = 0
        for word in words:
            node: dict[Any, Any] = root
            length = len(word)
            for i in range(length):
                key = (word[i], word[length - 1 - i])
                if key not in node:
                    node[key] = {}
                node = node[key]
                total += node.get("", 0)
            node[""] = node.get("", 0) + 1
        return total
```

## Complexity

| Time | Space |
| - | - |
| O(total chars), each character pair inserted/visited once | O(total chars) for the paired trie |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.