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.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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 <= 501 <= words[i].length <= 10words[i] consists only of lowercase English letters.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 #3042: Count Prefix and Suffix Pairs I
class Solution {
public int countPrefixSuffixPairs(String[] words) {
int ans = 0;
int n = words.length;
for (int i = 0; i < n; ++i) {
String s = words[i];
for (int j = i + 1; j < n; ++j) {
String t = words[j];
if (t.startsWith(s) && t.endsWith(s)) {
++ans;
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #3042: Count Prefix and Suffix Pairs I
func countPrefixSuffixPairs(words []string) (ans int) {
for i, s := range words {
for _, t := range words[i+1:] {
if strings.HasPrefix(t, s) && strings.HasSuffix(t, s) {
ans++
}
}
}
return
}
# Accepted solution for LeetCode #3042: Count Prefix and Suffix Pairs I
class Solution:
def countPrefixSuffixPairs(self, words: List[str]) -> int:
ans = 0
for i, s in enumerate(words):
for t in words[i + 1 :]:
ans += t.endswith(s) and t.startswith(s)
return ans
// Accepted solution for LeetCode #3042: Count Prefix and Suffix Pairs I
fn count_prefix_suffix_pairs(words: Vec<String>) -> i32 {
fn is_prefix_and_suffix(s1: &str, s2: &str) -> bool {
s2.starts_with(s1) && s2.ends_with(s1)
}
let len = words.len();
let mut ret = 0;
for i in 0..(len - 1) {
for j in (i + 1)..len {
if is_prefix_and_suffix(&words[i], &words[j]) {
ret += 1;
}
}
}
ret
}
fn main() {
let words = vec![
"a".to_string(),
"aba".to_string(),
"ababa".to_string(),
"aa".to_string(),
];
let ret = count_prefix_suffix_pairs(words);
println!("ret={ret}");
}
#[test]
fn test() {
{
let words = vec![
"a".to_string(),
"aba".to_string(),
"ababa".to_string(),
"aa".to_string(),
];
let ret = count_prefix_suffix_pairs(words);
assert_eq!(ret, 4);
}
{
let words = vec![
"pa".to_string(),
"papa".to_string(),
"ma".to_string(),
"mama".to_string(),
];
let ret = count_prefix_suffix_pairs(words);
assert_eq!(ret, 2);
}
{
let words = vec!["abab".to_string(), "ab".to_string()];
let ret = count_prefix_suffix_pairs(words);
assert_eq!(ret, 0);
}
}
// Accepted solution for LeetCode #3042: Count Prefix and Suffix Pairs I
function countPrefixSuffixPairs(words: string[]): number {
let ans = 0;
for (let i = 0; i < words.length; ++i) {
const s = words[i];
for (const t of words.slice(i + 1)) {
if (t.startsWith(s) && t.endsWith(s)) {
++ans;
}
}
}
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.