We are given a string S, we need to find count of all contiguous substrings starting and ending with same character.
Examples :
Input : S = "abcab"
Output : 7
There are 15 substrings of "abcab"
a, ab, abc, abca, abcab, b, bc, bca
bcab, c, ca, cab, a, ab, b
Out of the above substrings, there
are 7 substrings : a, abca, b, bcab,
c, a and b.
Input : S = "aba"
Output : 4
The substrings are a, b, a and aba
We have discussed different solutions in below post.
Count substrings with same first and last characters
In this article, a simple recursive solution is discussed.
Implementation:
C++
#include <iostream>
#include <string>
using namespace std;
int countSubstrs(string str, int i, int j, int n)
{
if (n == 1)
return 1;
if (n <= 0)
return 0;
int res = countSubstrs(str, i + 1, j, n - 1) +
countSubstrs(str, i, j - 1, n - 1) -
countSubstrs(str, i + 1, j - 1, n - 2);
if (str[i] == str[j])
res++;
return res;
}
int main()
{
string str = "abcab" ;
int n = str.length();
cout << countSubstrs(str, 0, n - 1, n);
}
|
Java
class GFG
{
static int countSubstrs(String str, int i,
int j, int n)
{
if (n == 1 )
return 1 ;
if (n <= 0 )
return 0 ;
int res = countSubstrs(str, i + 1 , j, n - 1 ) +
countSubstrs(str, i, j - 1 , n - 1 ) -
countSubstrs(str, i + 1 , j - 1 , n - 2 );
if (str.charAt(i) == str.charAt(j))
res++;
return res;
}
public static void main (String[] args)
{
String str = "abcab" ;
int n = str.length();
System.out.print(countSubstrs(str, 0 , n - 1 , n));
}
}
|
Python3
def countSubstrs( str , i, j, n):
if (n = = 1 ):
return 1
if (n < = 0 ):
return 0
res = (countSubstrs( str , i + 1 , j, n - 1 )
+ countSubstrs( str , i, j - 1 , n - 1 )
- countSubstrs( str , i + 1 , j - 1 , n - 2 ))
if ( str [i] = = str [j]):
res + = 1
return res
str = "abcab"
n = len ( str )
print (countSubstrs( str , 0 , n - 1 , n))
|
Javascript
<script>
function countSubstrs(str, i, j, n)
{
if (n == 1)
return 1;
if (n <= 0)
return 0;
let res = countSubstrs(str, i + 1, j, n - 1) +
countSubstrs(str, i, j - 1, n - 1) -
countSubstrs(str, i + 1, j - 1, n - 2);
if (str[i] == str[j])
res++;
return res;
}
let str = "abcab" ;
let n = str.length;
document.write(countSubstrs(str, 0, n - 1, n));
</script>
|
C#
using System;
class GFG {
static int countSubstrs( string str, int i,
int j, int n)
{
if (n == 1)
return 1;
if (n <= 0)
return 0;
int res = countSubstrs(str, i + 1, j, n - 1)
+ countSubstrs(str, i, j - 1, n - 1)
- countSubstrs(str, i + 1, j - 1, n - 2);
if (str[i] == str[j])
res++;
return res;
}
public static void Main ()
{
string str = "abcab" ;
int n = str.Length;
Console.WriteLine(
countSubstrs(str, 0, n - 1, n));
}
}
|
PHP
<?php
function countSubstrs( $str , $i ,
$j , $n )
{
if ( $n == 1)
return 1;
if ( $n <= 0)
return 0;
$res = countSubstrs( $str , $i + 1, $j , $n - 1) +
countSubstrs( $str , $i , $j - 1, $n - 1) -
countSubstrs( $str , $i + 1, $j - 1, $n - 2);
if ( $str [ $i ] == $str [ $j ])
$res ++;
return $res ;
}
$str = "abcab" ;
$n = strlen ( $str );
echo (countSubstrs( $str , 0, $n - 1, $n ));
?>
|
The time complexity of above solution is exponential. In Worst case, we may end up doing O(3n) operations.
Auxiliary Space: O(n), where n is the length of string.
This is because when string is passed in the function it creates a copy of itself in stack.

There is also a divide and conquer recursive approach
The idea is to split the string in half until we get one element and have our base case return 2 things
- a map containing the character to the number of occurrences (i.e a:1 since its the base case)
- (This is the total number of substring with start and end with the same char. Since the base case is a string of size one, it starts and ends with the same character)
Then combine the solutions of the left and right division of the string, then return a new solution based on left and right. This new solution can be constructed by multiplying the common characters between the left and right set and adding to the solution count from left and right, and returning a map containing element occurrence count and solution count
Implementation:
Java
import java.util.HashMap;
import java.util.Map;
public class CountSubstr {
public static void main(String[] args)
{
System.out.println(countSubstr( "abcab" ));
}
public static int countSubstr(String s)
{
if (s.length() == 0 ) {
return 0 ;
}
Map<Character, Integer> charMap = new HashMap<>();
int [] numSubstr = { 0 };
countSubstrHelper(s, 0 , s.length() - 1 , charMap,
numSubstr);
return numSubstr[ 0 ];
}
public static void
countSubstrHelper(String string, int start, int end,
Map<Character, Integer> charMap,
int [] numSubstr)
{
if (start
>= end) {
charMap.put(string.charAt(start), 1 );
numSubstr[ 0 ] = 1 ;
return ;
}
int mid = (start + end) / 2 ;
Map<Character, Integer> mapLeft = new HashMap<>();
int [] numSubstrLeft = { 0 };
countSubstrHelper(
string, start, mid, mapLeft,
numSubstrLeft);
Map<Character, Integer> mapRight = new HashMap<>();
int [] numSubstrRight = { 0 };
countSubstrHelper(
string, mid + 1 , end, mapRight,
numSubstrRight);
numSubstr[ 0 ] = numSubstrLeft[ 0 ] + numSubstrRight[ 0 ];
for ( char ch : mapLeft.keySet()) {
if (mapRight.containsKey(ch)) {
numSubstr[ 0 ]
+= mapLeft.get(ch) * mapRight.get(ch);
}
}
for ( char ch : mapRight.keySet()) {
if (mapLeft.containsKey(ch)) {
mapLeft.put(ch, mapLeft.get(ch)
+ mapRight.get(ch));
}
else {
mapLeft.put(ch, mapRight.get(ch));
}
}
charMap.putAll(mapLeft);
}
}
|
Python3
def countSubstr(s):
if len (s) = = 0 :
return 0
charMap, numSubstr = countSubstrHelper(s, 0 , len (s) - 1 )
return numSubstr
def countSubstrHelper(string, start, end):
if start > = end:
return {string[start]: 1 }, 1
mid = (start + end) / / 2
mapLeft, numSubstrLeft = countSubstrHelper(
string, start, mid)
mapRight, numSubstrRight = countSubstrHelper(
string, mid + 1 , end)
numSubstrSelf = numSubstrLeft + numSubstrRight
for char in mapLeft:
if char in mapRight:
numSubstrSelf + = mapLeft[char] * mapRight[char]
for char in mapRight:
if char in mapLeft:
mapLeft[char] + = mapRight[char]
else :
mapLeft[char] = mapRight[char]
return mapLeft, numSubstrSelf
print (countSubstr( "abcab" ))
|
Javascript
function countSubstr(s) {
if (s.length == 0) {
return 0;
}
let [charMap, numSubstr] = countSubstrHelper(s, 0, s.length - 1);
return numSubstr;
}
function countSubstrHelper(string, start, end) {
if (start >= end) {
return [{ [string[start]]: 1 }, 1];
}
let mid = Math.floor((start + end) / 2);
let [mapLeft, numSubstrLeft] = countSubstrHelper(string, start, mid);
let [mapRight, numSubstrRight] = countSubstrHelper(string, mid + 1, end);
let numSubstrSelf = numSubstrLeft + numSubstrRight;
for (let char in mapLeft) {
if (char in mapRight) {
numSubstrSelf += mapLeft[char] * mapRight[char];
}
}
for (let char in mapRight) {
if (char in mapLeft) {
mapLeft[char] += mapRight[char];
} else {
mapLeft[char] = mapRight[char];
}
}
return [mapLeft, numSubstrSelf];
}
console.log(countSubstr( "abcab" ));
|
C#
using System;
using System.Collections.Generic;
public class CountSubstr {
public static void Main( string [] args)
{
Console.WriteLine(countSubstr( "abcab" ));
}
public static int countSubstr( string s)
{
if (s.Length == 0) {
return 0;
}
Dictionary< char , int > charMap
= new Dictionary< char , int >();
int [] numSubstr = { 0 };
countSubstrHelper(s, 0, s.Length - 1, charMap,
numSubstr);
return numSubstr[0];
}
public static void
countSubstrHelper( string s, int start, int end,
Dictionary< char , int > charMap,
int [] numSubstr)
{
if (start >= end) {
charMap[s[start]] = 1;
numSubstr[0] = 1;
return ;
}
int mid = (start + end) / 2;
Dictionary< char , int > mapLeft
= new Dictionary< char , int >();
int [] numSubstrLeft = { 0 };
countSubstrHelper(
s, start, mid, mapLeft,
numSubstrLeft);
Dictionary< char , int > mapRight
= new Dictionary< char , int >();
int [] numSubstrRight = { 0 };
countSubstrHelper(
s, mid + 1, end, mapRight,
numSubstrRight);
numSubstr[0] = numSubstrLeft[0] + numSubstrRight[0];
foreach ( char ch in mapLeft.Keys)
{
if (mapRight.ContainsKey(ch)) {
numSubstr[0] += mapLeft[ch] * mapRight[ch];
}
}
foreach ( char ch in mapRight.Keys)
{
if (mapLeft.ContainsKey(ch)) {
mapLeft[ch] = mapLeft[ch] + mapRight[ch];
}
else {
mapLeft[ch] = mapRight[ch];
}
}
foreach (KeyValuePair< char , int > entry in mapLeft)
{
charMap[entry.Key] = entry.Value;
}
}
}
|
C++
#include <iostream>
#include <unordered_map>
using namespace std;
void countSubstrHelper(string s, int start, int end,
unordered_map< char , int >& charMap,
int & numSubstr)
{
if (start >= end) {
charMap[s[start]] = 1;
numSubstr = 1;
return ;
}
int mid = (start + end) / 2;
unordered_map< char , int > mapLeft, mapRight;
int numSubstrLeft = 0, numSubstrRight = 0;
countSubstrHelper(s, start, mid, mapLeft,
numSubstrLeft);
countSubstrHelper(
s, mid + 1, end, mapRight,
numSubstrRight);
numSubstr = numSubstrLeft + numSubstrRight;
for ( auto it = mapLeft.begin(); it != mapLeft.end();
++it) {
if (mapRight.find(it->first) != mapRight.end()) {
numSubstr += it->second * mapRight[it->first];
}
}
for ( auto it = mapRight.begin(); it != mapRight.end();
++it) {
if (mapLeft.find(it->first) != mapLeft.end()) {
mapLeft[it->first] += it->second;
}
else {
mapLeft[it->first] = it->second;
}
}
charMap = mapLeft;
}
int countSubstr(string s)
{
if (s.length() == 0) {
return 0;
}
unordered_map< char , int > charMap;
int numSubstr = 0;
countSubstrHelper(s, 0, s.length() - 1, charMap,
numSubstr);
return numSubstr;
}
int main()
{
cout << countSubstr( "abcab" ) << endl;
return 0;
}
|
The time complexity of the above solution is O(nlogn) with space complexity O(n) which occurs if all elements are distinct
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
04 Apr, 2023
Like Article
Save Article