#3045

Count Prefix and Suffix Pairs II

Hard
ArrayStringTrieRolling HashString MatchingHash Function
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute-force approach checks every possible pair of words to see if one is both a prefix and a suffix of the other. This is straightforward but inefficient for larger inputs.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a counter to zero.
  2. 2Step 2: Loop through each pair of words (i, j) where i < j.
  3. 3Step 3: For each pair, check if words[i] is a prefix and a suffix of words[j] using the isPrefixAndSuffix function.
  4. 4Step 4: If true, increment the counter.
  5. 5Step 5: Return the counter.
solution.py17 lines
1# Full working Python code
2
3def isPrefixAndSuffix(str1, str2):
4    return str2.startswith(str1) and str2.endswith(str1)
5
6def countPairs(words):
7    count = 0
8    n = len(words)
9    for i in range(n):
10        for j in range(i + 1, n):
11            if isPrefixAndSuffix(words[i], words[j]):
12                count += 1
13    return count
14
15# Example usage
16words = ['a', 'aba', 'ababa', 'aa']
17print(countPairs(words))

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.