Given a string str consisting of lowercase English alphabets, the task is to find the total number of palindromic sub-strings present in the sorted form of str.
Input: str = “acbbd”
All palindromic sub-string in it’s sorted form (“abbcd”) are “a”, “b”, “b”, “bb”, “c” and “d”.
Input: str = “abbabdbd”
Naive approach: One way is to sort the given string and then count the total number of sub-strings present which are palindromes. For finding number of palindromic sub-strings this approach can be used which has time complexity of O(n^2).
Optimized approach: An efficient way is to count the frequency of each character and then for each frequency total number of palindromes will (n*(n+1))/2 as all the palindromic sub-strings of a sorted string will consist of the same character.
For example, palindromic sub-string for the string “aabbbcd” will be “a”, “aa”, …, “bbb”, “c”, … etc. Time complexity for this approach will be O(n).
- Create a hash table for storing the frequencies of each character of the string str.
- Traverse the hash table and for each non-zero frequency add (hash[i] * (hash[i]+1)) / 2 to the sum.
- Print the sum in the end.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Longest palindromic string possible after removal of a substring
- Find if a given string can be represented from a substring by iterating the substring “n” times
- Minimum length of substring whose rotation generates a palindromic substring
- Longest Palindromic Substring using Palindromic Tree | Set 3
- Count All Palindromic Subsequence in a given String
- Count palindromic characteristics of a String
- Count pairs of non-overlapping palindromic sub-strings of the given string
- Permutation of given string that maximizes count of Palindromic substrings
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Find a palindromic string B such that given String A is a subsequense of B
- Find length of longest subsequence of one string which is substring of another string
- Find all palindromic sub-strings of a given string | Set 2
- Find all distinct palindromic sub-strings of a given string
- Decode a string recursively encoded as count followed by substring
- Find the lexicographically largest palindromic Subsequence of a String
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.