#3042
Easy Algorithms Count prefix and suffix pairs i
Array String Trie Rolling Hash String Matching Hash Function
77.8% acceptance
Feb 25, 2026
602
45
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.
Return an integer denoting the number of index pairs (i, j) such that i < j, and isPrefixAndSuffix(words[i], words[j]) is true.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn count_prefix_suffix_pairs(words: Vec<String>) -> i32 {
let n = words.len();
let mut ans = 0;
for i in 0..n {
for j in (i+1)..n {
let s = &words[i];
let t = &words[j];
if t.starts_with(s.as_str()) && t.ends_with(s.as_str()) { ans += 1; }
}
}
ans
}
}