Recursive solution to count substrings with same first and last characters
Last Updated :
04 Apr, 2023
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++
// c++ program to count substrings with same
// first and last characters
#include <iostream>
#include <string>
using namespace std;
/* Function to count substrings with same first and
last characters*/
int countSubstrs(string str, int i, int j, int n)
{
// base cases
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;
}
// driver code
int main()
{
string str = "abcab";
int n = str.length();
cout << countSubstrs(str, 0, n - 1, n);
}
Java
// Java program to count substrings
// with same first and last characters
class GFG
{
// Function to count substrings
// with same first and
// last characters
static int countSubstrs(String str, int i,
int j, int n)
{
// base cases
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;
}
// Driver code
public static void main (String[] args)
{
String str = "abcab";
int n = str.length();
System.out.print(countSubstrs(str, 0, n - 1, n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python 3 program to count substrings with same
# first and last characters
# Function to count substrings with same first and
# last characters
def countSubstrs(str, i, j, n):
# base cases
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
# driver code
str = "abcab"
n = len(str)
print(countSubstrs(str, 0, n - 1, n))
# This code is contributed by Smitha
JavaScript
<script>
// Javascript program to count substrings
// with same first and last characters
// Function to count substrings
// with same first and
// last characters
function countSubstrs(str, i, j, n)
{
// Base cases
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;
}
// Driver code
let str = "abcab";
let n = str.length;
document.write(countSubstrs(str, 0, n - 1, n));
// This code is contributed by rameshtravel07
</script>
C#
// C# program to count substrings
// with same first and last characters
using System;
class GFG {
// Function to count substrings
// with same first and
// last characters
static int countSubstrs(string str, int i,
int j, int n)
{
// base cases
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;
}
// Driver code
public static void Main ()
{
string str = "abcab";
int n = str.Length;
Console.WriteLine(
countSubstrs(str, 0, n - 1, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to count
// substrings with same
// first and last characters
//Function to count substrings
// with same first and
// last characters
function countSubstrs($str, $i,
$j, $n)
{
// base cases
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;
}
// Driver Code
$str = "abcab";
$n = strlen($str);
echo(countSubstrs($str, 0, $n - 1, $n));
// This code is contributed by Ajit.
?>
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) { // our base case for the recursion.
// When we have one character
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); // solve the left half
Map<Character, Integer> mapRight = new HashMap<>();
int[] numSubstrRight = { 0 };
countSubstrHelper(
string, mid + 1, end, mapRight,
numSubstrRight); // solve the right half
// add number of substrings from left and right
numSubstr[0] = numSubstrLeft[0] + numSubstrRight[0];
// multiply the characters from left set with
// matching characters from right set then add to
// total number of substrings
for (char ch : mapLeft.keySet()) {
if (mapRight.containsKey(ch)) {
numSubstr[0]
+= mapLeft.get(ch) * mapRight.get(ch);
}
}
// Add all the key,value pairs from right map to
// left map
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));
}
}
// Return the map of character and the sum of
// substring from left, right and self
charMap.putAll(mapLeft);
}
}
Python3
# code
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: # our base case for the recursion. When we have one character
return {string[start]: 1}, 1
mid = (start + end)//2
mapLeft, numSubstrLeft = countSubstrHelper(
string, start, mid) # solve the left half
mapRight, numSubstrRight = countSubstrHelper(
string, mid+1, end) # solve the right half
# add number of substrings from left and right
numSubstrSelf = numSubstrLeft + numSubstrRight
# multiply the characters from left set with matching characters from right set
# then add to total number of substrings
for char in mapLeft:
if char in mapRight:
numSubstrSelf += mapLeft[char] * mapRight[char]
# Add all the key,value pairs from right map to left map
for char in mapRight:
if char in mapLeft:
mapLeft[char] += mapRight[char]
else:
mapLeft[char] = mapRight[char]
# Return the map of character and the sum of substring from left, right and self
return mapLeft, numSubstrSelf
print(countSubstr("abcab"))
# Contributed by Xavier Jean Baptiste
JavaScript
// JavaScript code
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) {
// our base case for the recursion. When we have one character
if (start >= end) {
return [{ [string[start]]: 1 }, 1];
}
let mid = Math.floor((start + end) / 2);
// solve the left half
let [mapLeft, numSubstrLeft] = countSubstrHelper(string, start, mid);
// solve the right half
// add number of substrings from left and right
let [mapRight, numSubstrRight] = countSubstrHelper(string, mid + 1, end);
let numSubstrSelf = numSubstrLeft + numSubstrRight;
// multiply the characters from left set with matching characters from right set
// then add to total number of substrings
for (let char in mapLeft) {
if (char in mapRight) {
numSubstrSelf += mapLeft[char] * mapRight[char];
}
}
// Add all the key,value pairs from right map to left map
for (let char in mapRight) {
if (char in mapLeft) {
mapLeft[char] += mapRight[char];
} else {
mapLeft[char] = mapRight[char];
}
}
// Return the map of character and the sum of substring from left, right and self
return [mapLeft, numSubstrSelf];
}
console.log(countSubstr("abcab"));
// This code is contributed by adityashatmfh
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) {
// our base case for the recursion. When we have
// one character
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); // solve the left half
Dictionary<char, int> mapRight
= new Dictionary<char, int>();
int[] numSubstrRight = { 0 };
countSubstrHelper(
s, mid + 1, end, mapRight,
numSubstrRight); // solve the right half
// add number of substrings from left and right
numSubstr[0] = numSubstrLeft[0] + numSubstrRight[0];
// multiply the characters from left set with
// matching characters from right set then add to
// total number of substrings
foreach(char ch in mapLeft.Keys)
{
if (mapRight.ContainsKey(ch)) {
numSubstr[0] += mapLeft[ch] * mapRight[ch];
}
}
// Add all the key,value pairs from right map to
// left map
foreach(char ch in mapRight.Keys)
{
if (mapLeft.ContainsKey(ch)) {
mapLeft[ch] = mapLeft[ch] + mapRight[ch];
}
else {
mapLeft[ch] = mapRight[ch];
}
}
// Return the map of character and the sum of
// substring from left, right and self
foreach(KeyValuePair<char, int> entry in mapLeft)
{
charMap[entry.Key] = entry.Value;
}
}
}
// This code in contributed by shiv1o43g
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) { // base case
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); // solve the left half
countSubstrHelper(
s, mid + 1, end, mapRight,
numSubstrRight); // solve the right half
// add number of substrings from left and right
numSubstr = numSubstrLeft + numSubstrRight;
// multiply the characters from left set with matching
// characters from right set then add to total number of
// substrings
for (auto it = mapLeft.begin(); it != mapLeft.end();
++it) {
if (mapRight.find(it->first) != mapRight.end()) {
numSubstr += it->second * mapRight[it->first];
}
}
// Add all the key,value pairs from right map to left
// map
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;
}
}
// Return the map of character and the sum of substring
// from left, right and self
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;
}
// This code is contributed by shivhack999
The time complexity of the above solution is O(nlogn) with space complexity O(n) which occurs if all elements are distinct
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem