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$
scontains 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:
fsingle-character substringsfC2substrings 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