LeetCode 3045: Count Prefix and Suffix Pairs II Solution
Master LeetCode problem 3045 (Count Prefix and Suffix Pairs II), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3045. Count Prefix and Suffix Pairs II
Problem Explanation
Explanation
To solve this problem, we can iterate through each pair of words and check if one word is a prefix and suffix of the other. We can achieve this by comparing the lengths of the two words and then checking for prefix and suffix equality.
- Iterate through all pairs of words.
- For each pair, check if the first word is a prefix and suffix of the second word.
- Keep track of the count of valid pairs.
Time complexity: O(n^2 * min(m1, m2)) where n is the number of words and m1, m2 are the lengths of the two words being compared. Space complexity: O(1)
Solution Code
class Solution {
public int countPrefixAndSuffixPairs(String[] words) {
int count = 0;
for (int i = 0; i < words.length; i++) {
for (int j = i + 1; j < words.length; j++) {
if (isPrefixAndSuffix(words[i], words[j])) {
count++;
}
}
}
return count;
}
private boolean isPrefixAndSuffix(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
if (len1 > len2) {
return isPrefixAndSuffix(word2, word1); // Ensure word1 is shorter
}
for (int i = 0; i < len1; i++) {
if (word1.charAt(i) != word2.charAt(len2 - len1 + i)) {
return false;
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3045 (Count Prefix and Suffix Pairs II)?
This page provides optimized solutions for LeetCode problem 3045 (Count Prefix and Suffix Pairs II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3045 (Count Prefix and Suffix Pairs II)?
The time complexity for LeetCode 3045 (Count Prefix and Suffix Pairs II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3045 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3045 in Java, C++, or Python.