LeetCode 2955: Number of Same-End Substrings Solution

Master LeetCode problem 2955 (Number of Same-End Substrings), a medium 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.

2955. Number of Same-End Substrings

Problem Explanation

Explanation:

Given a string, we need to find the number of substrings where both the start and end characters are the same.

To solve this problem, we can iterate through each character in the string and consider it as the potential start of the substring. For each character, we then iterate through the rest of the string to find all substrings that have the same start and end character.

Example:

Let's consider the input string "abcab".

  1. For the character 'a' at index 0, we find 2 substrings with the same start and end character: "a" and "abca".
  2. For the character 'b' at index 1, we find 1 substring: "b".
  3. For the character 'c' at index 2, we find 1 substring: "c".
  4. For the character 'a' at index 3, we find 1 substring: "a".

Total number of same-end substrings: 5

Time Complexity:

The time complexity of this approach is O(n^2), where n is the length of the input string.

Space Complexity:

The space complexity of this approach is O(1) as we are not using any extra space proportional to the input size.

:

Solution Code

class Solution {
    public int countEndSubstrings(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            for (int j = i; j < s.length(); j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    count++;
                }
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2955 (Number of Same-End Substrings)?

This page provides optimized solutions for LeetCode problem 2955 (Number of Same-End Substrings) 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 2955 (Number of Same-End Substrings)?

The time complexity for LeetCode 2955 (Number of Same-End Substrings) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2955 on DevExCode?

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

Back to LeetCode Solutions