Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Example 1:
Input: words = ["a","aba","ababa","aa"]
Output: 4
Explanation: In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.
i = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.
i = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.
i = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.
Therefore, the answer is 4.
Example 2:
Input: words = ["pa","papa","ma","mama"]
Output: 2
Explanation: In this example, the counted index pairs are:
i = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.
i = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.
Therefore, the answer is 2.
Example 3:
Input: words = ["abab","ab"]
Output: 0
Explanation: In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.
Therefore, the answer is 0.
Constraints:
1 <= words.length <= 1051 <= words[i].length <= 105words[i] consists only of lowercase English letters.words[i] does not exceed 5 * 105.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Trie · String Matching
["a","aba","ababa","aa"]
["pa","papa","ma","mama"]
["abab","ab"]
implement-trie-prefix-tree)design-add-and-search-words-data-structure)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3045: Count Prefix and Suffix Pairs II
class Node {
Map<Integer, Node> children = new HashMap<>();
int cnt;
}
class Solution {
public long countPrefixSuffixPairs(String[] words) {
long ans = 0;
Node trie = new Node();
for (String s : words) {
Node node = trie;
int m = s.length();
for (int i = 0; i < m; ++i) {
int p = s.charAt(i) * 32 + s.charAt(m - i - 1);
node.children.putIfAbsent(p, new Node());
node = node.children.get(p);
ans += node.cnt;
}
++node.cnt;
}
return ans;
}
}
// Accepted solution for LeetCode #3045: Count Prefix and Suffix Pairs II
type Node struct {
children map[int]*Node
cnt int
}
func countPrefixSuffixPairs(words []string) (ans int64) {
trie := &Node{children: make(map[int]*Node)}
for _, s := range words {
node := trie
m := len(s)
for i := 0; i < m; i++ {
p := int(s[i])*32 + int(s[m-i-1])
if _, ok := node.children[p]; !ok {
node.children[p] = &Node{children: make(map[int]*Node)}
}
node = node.children[p]
ans += int64(node.cnt)
}
node.cnt++
}
return
}
# Accepted solution for LeetCode #3045: Count Prefix and Suffix Pairs II
class Node:
__slots__ = ["children", "cnt"]
def __init__(self):
self.children = {}
self.cnt = 0
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
ans = 0
trie = Node()
for s in words:
node = trie
for p in zip(s, reversed(s)):
if p not in node.children:
node.children[p] = Node()
node = node.children[p]
ans += node.cnt
node.cnt += 1
return ans
// Accepted solution for LeetCode #3045: Count Prefix and Suffix Pairs II
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3045: Count Prefix and Suffix Pairs II
// class Node {
// Map<Integer, Node> children = new HashMap<>();
// int cnt;
// }
//
// class Solution {
// public long countPrefixSuffixPairs(String[] words) {
// long ans = 0;
// Node trie = new Node();
// for (String s : words) {
// Node node = trie;
// int m = s.length();
// for (int i = 0; i < m; ++i) {
// int p = s.charAt(i) * 32 + s.charAt(m - i - 1);
// node.children.putIfAbsent(p, new Node());
// node = node.children.get(p);
// ans += node.cnt;
// }
// ++node.cnt;
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #3045: Count Prefix and Suffix Pairs II
class Node {
children: Map<number, Node> = new Map<number, Node>();
cnt: number = 0;
}
function countPrefixSuffixPairs(words: string[]): number {
let ans: number = 0;
const trie: Node = new Node();
for (const s of words) {
let node: Node = trie;
const m: number = s.length;
for (let i: number = 0; i < m; ++i) {
const p: number = s.charCodeAt(i) * 32 + s.charCodeAt(m - i - 1);
if (!node.children.has(p)) {
node.children.set(p, new Node());
}
node = node.children.get(p)!;
ans += node.cnt;
}
++node.cnt;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Store all N words in a hash set. Each insert/lookup hashes the entire word of length L, giving O(L) per operation. Prefix queries require checking every stored word against the prefix — O(N × L) per prefix search. Space is O(N × L) for storing all characters.
Each operation (insert, search, prefix) takes O(L) time where L is the word length — one node visited per character. Total space is bounded by the sum of all stored word lengths. Tries win over hash sets when you need prefix matching: O(L) prefix search vs. checking every stored word.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.