![]() |
VOOZH | about |
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:
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.
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
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:
7
The time complexity of the above solution is O(nlogn) with space complexity O(n) which occurs if all elements are distinct