15. Substrings with Same First and Last Characters
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given a string s
consisting of lowercase English letters, count all substrings in which the first and last characters are the same.
A substring is a contiguous sequence of characters within the string. Single-character substrings are always valid.
๐ Examples
Example 1:
Input:
s = "abcab"
Output:
7
Explanation:
The valid substrings are "a"
, "b"
, "c"
, "a"
, "b"
, "abca"
, and "bcab"
.
Example 2:
Input:
s = "aba"
Output:
4
Explanation:
The valid substrings are "a"
, "b"
, "a"
, and "aba"
.
๐ Constraints
$1 \leq |s| \leq 10^4$
s
contains only lowercase English alphabets ('a'
to'z'
)
โ
My Approach
Frequency Count using Combinatorics
A substring starts and ends with the same character if we consider all positions where a character appears. For a character appearing f
times, the number of such substrings is:
This accounts for:
f
single-character substringsfC2
substrings where both ends are the same character
We use a frequency array of size 256 (or 26 if lowercase only) to count characters, then sum this formula over all counts.
๐งฎ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we scan the string once to count character frequencies and once more to sum results.
Expected Auxiliary Space Complexity: O(1), as we use a fixed-size array of length 256 regardless of input size.
๐ง Code (C++)
class Solution {
public:
int countSubstring(string &s) {
long long cnt[256]={}, ans=0;
for(char c:s) cnt[(unsigned char)c]++;
for(int i=0;i<256;i++)
ans += cnt[i]*(cnt[i]+1)/2;
return (int)ans;
}
};
๐งโ๐ป Code (Java)
class Solution {
public int countSubstring(String s) {
int[] cnt = new int[256];
long ans = 0;
for (char c : s.toCharArray()) cnt[c]++;
for (int x : cnt) ans += (long)x * (x + 1) / 2;
return (int)ans;
}
}
๐ Code (Python)
class Solution:
def countSubstring(self, s):
from collections import Counter
return sum(v * (v + 1) // 2 for v in Counter(s).values())
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated