![]() |
VOOZH | about |
Given a string s, find the total number of palindromic substrings of length greater than or equal to 2 present in the string.
A substring is palindromic if it reads the same forwards and backwards.
Examples:
Input: s = "abaab"
Output: 3
Explanation: Palindrome substrings (of length > 1) are "aba" , "aa" , "baab"Input : s = "aaa"
Output: 3
Explanation : Palindrome substrings (of length > 1) are "aa" , "aa" , "aaa"Input : s = "abbaeae"
Output: 4
Explanation : Palindrome substrings (of length > 1) are "bb" , "abba" , "aea", "eae"
Table of Content
Note: We have already discussed a naive and dynamic programming based solution in the article Count All Palindrome Sub-Strings in a String.
The idea is to consider each character of the given string as midpoint of a palindrome and expand it in both directions to find all palindromes of even and odd lengths.
4
We use Manacher’s algorithm to find all palindromic substrings in linear time by computing the maximum radius of palindromes centered at each character (after modifying the string with separators). For each center, the number of palindromic substrings is proportional to half the radius. After summing over all centers, we subtract palindromic substrings of length 1 to count only those of length ≥ 2.
Step by Step Implementation:
4
Time Complexity: O(n)
Auxiliary Space: O(n), additional space is used for the modified string ms and the palindrome radius array p, both of size proportional to the original string length.