LeetCode 3042: Count Prefix and Suffix Pairs I Solution

Master LeetCode problem 3042 (Count Prefix and Suffix Pairs I), a easy 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.

3042. Count Prefix and Suffix Pairs I

Problem Explanation

Explanation:

To solve this problem, we can iterate through all pairs of words and check if one word is a prefix and suffix of the other word. We can do this by checking if the second word starts with the first word and ends with the first word.

Algorithm:

  1. Initialize a variable count to 0 to keep track of the number of valid index pairs.
  2. Iterate through all pairs of words using two nested loops.
  3. For each pair of words, check if the first word is a prefix and suffix of the second word.
  4. If the condition is met, increment the count.
  5. Return the final count as the result.

Time Complexity:

The time complexity of this algorithm is O(n^2), where n is the number of words in the input array.

Space Complexity:

The space complexity of this algorithm is O(1) as we are not using any extra space.

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 (words[j].startsWith(words[i]) && words[j].endsWith(words[i])) {
                    count++;
                }
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3042 (Count Prefix and Suffix Pairs I)?

This page provides optimized solutions for LeetCode problem 3042 (Count Prefix and Suffix Pairs I) 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 3042 (Count Prefix and Suffix Pairs I)?

The time complexity for LeetCode 3042 (Count Prefix and Suffix Pairs I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3042 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3042 in Java, C++, or Python.

Back to LeetCode Solutions