VOOZH about

URL: https://www.geeksforgeeks.org/dsa/recursive-solution-count-substrings-first-last-characters/

⇱ Recursive solution to count substrings with same first and last characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Recursive solution to count substrings with same first and last characters

Last Updated : 4 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:


Output
7


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.
 

👁 Image


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

  1. a map containing the character to the number of occurrences (i.e a:1 since its the base case)
  2. (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:


Output
7

The time complexity of the above solution is O(nlogn) with space complexity O(n) which occurs if all elements are distinct

Comment
Article Tags: