Given a string s consisting of lowercase characters, the task is to find the count of all substrings that start and end with the same character.
Examples :
Input : s = "abcab"
Output : 7
Explanation: The substrings are "a", "abca", "b", "bcab", "c", "a", "b".
Input : s = "aba"
Output : 4
Explanation: The substrings are "a", "aba", "b", and "a".
[Naive Approach] Using Two Nested Loops - O(n^2) time and O(1) space
The idea is to check each possible substring in the string and count those that have the same first and last character.
// C++ program to count all substrings with same
// first and last characters.
#include <bits/stdc++.h>
using namespace std;
int countSubstring(string s) {
int count = 0;
int n = s.length();
// Consider all possible substrings
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
// If first and last characters
// of substring s[i..j] are same
if (s[i] == s[j]) {
count++;
}
}
}
return count;
}
int main() {
string s = "abcab";
cout << countSubstring(s);
return 0;
}
// Java program to count all substrings with same
// first and last characters.
class GfG {
static int countSubstring(String s) {
int count = 0;
int n = s.length();
// Consider all possible substrings
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
// If first and last characters
// of substring s[i..j] are same
if (s.charAt(i) == s.charAt(j)) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
String s = "abcab";
System.out.println(countSubstring(s));
}
}
# Python program to count all substrings with same
# first and last characters.
def countSubstring(s):
count = 0
n = len(s)
# Consider all possible substrings
for i in range(n):
for j in range(i, n):
# If first and last characters
# of substring s[i..j] are same
if s[i] == s[j]:
count += 1
return count
if __name__ == "__main__":
s = "abcab"
print(countSubstring(s))
// C# program to count all substrings with same
// first and last characters.
using System;
class GfG {
static int countSubstring(string s) {
int count = 0;
int n = s.Length;
// Consider all possible substrings
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
// If first and last characters
// of substring s[i..j] are same
if (s[i] == s[j]) {
count++;
}
}
}
return count;
}
static void Main() {
string s = "abcab";
Console.WriteLine(countSubstring(s));
}
}
// JavaScript program to count all substrings with same
// first and last characters.
function countSubstring(s) {
let count = 0;
let n = s.length;
// Consider all possible substrings
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
// If first and last characters
// of substring s[i..j] are same
if (s[i] === s[j]) {
count++;
}
}
}
return count;
}
let s = "abcab";
console.log(countSubstring(s));
Output
7
[Expected Approach] Using Character Frequency - O(n) time and O(1) space
The idea is to use the fact that for each character in the alphabet, we can directly calculate how many substrings would start and end with that character without actually generating all possible substrings. By counting the frequency of each character in the string, we can use the combination formula to determine how many ways we can select two occurrences of the same character to form the start and end of substrings, plus the substrings of length 1.
Step by step approach:
- Count the frequency of each lowercase letter in the input string.
- For each character that appears in the string, calculate the number of possible substrings using the formula n*(n+1)/2.
- Return the final sum as the total count of valid substrings.
// C++ program to count all substrings with same
// first and last characters.
#include <bits/stdc++.h>
using namespace std;
int countSubstring(string s) {
int n = s.length();
// Create an array to store
// frequency of characters
vector<int> freq(26, 0);
// Update frequency of each character
for (int i = 0; i < n; i++) {
freq[s[i] - 'a']++;
}
int count = 0;
// For each character, calculate number of substrings
// that start and end with that character
for (int i = 0; i < 26; i++) {
// Number of substrings with same
// first and last character is
// nC2 + n = n*(n+1)/2
count += (freq[i] * (freq[i] + 1)) / 2;
}
return count;
}
int main() {
string s = "abcab";
cout << countSubstring(s);
return 0;
}
// Java program to count all substrings with same
// first and last characters.
class GfG {
static int countSubstring(String s) {
int n = s.length();
// Create an array to store
// frequency of characters
int[] freq = new int[26];
// Update frequency of each character
for (int i = 0; i < n; i++) {
freq[s.charAt(i) - 'a']++;
}
int count = 0;
// For each character, calculate number of substrings
// that start and end with that character
for (int i = 0; i < 26; i++) {
// Number of substrings with same
// first and last character is
// nC2 + n = n*(n+1)/2
count += (freq[i] * (freq[i] + 1)) / 2;
}
return count;
}
public static void main(String[] args) {
String s = "abcab";
System.out.println(countSubstring(s));
}
}
# Python program to count all substrings with same
# first and last characters.
def countSubstring(s):
n = len(s)
# Create an array to store
# frequency of characters
freq = [0] * 26
# Update frequency of each character
for i in range(n):
freq[ord(s[i]) - ord('a')] += 1
count = 0
# For each character, calculate number of substrings
# that start and end with that character
for i in range(26):
# Number of substrings with same
# first and last character is
# nC2 + n = n*(n+1)/2
count += (freq[i] * (freq[i] + 1)) // 2
return count
if __name__ == "__main__":
s = "abcab"
print(countSubstring(s))
// C# program to count all substrings with same
// first and last characters.
using System;
class GfG {
static int countSubstring(string s) {
int n = s.Length;
// Create an array to store
// frequency of characters
int[] freq = new int[26];
// Update frequency of each character
for (int i = 0; i < n; i++) {
freq[s[i] - 'a']++;
}
int count = 0;
// For each character, calculate number of substrings
// that start and end with that character
for (int i = 0; i < 26; i++) {
// Number of substrings with same
// first and last character is
// nC2 + n = n*(n+1)/2
count += (freq[i] * (freq[i] + 1)) / 2;
}
return count;
}
static void Main() {
string s = "abcab";
Console.WriteLine(countSubstring(s));
}
}
// JavaScript program to count all substrings with same
// first and last characters.
function countSubstring(s) {
let n = s.length;
// Create an array to store
// frequency of characters
let freq = new Array(26).fill(0);
// Update frequency of each character
for (let i = 0; i < n; i++) {
freq[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;
}
let count = 0;
// For each character, calculate number of substrings
// that start and end with that character
for (let i = 0; i < 26; i++) {
// Number of substrings with same
// first and last character is
// nC2 + n = n*(n+1)/2
count += (freq[i] * (freq[i] + 1)) / 2;
}
return count;
}
let s = "abcab";
console.log(countSubstring(s));
Output
7
Related Articles: